国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

從零編寫一個Koa + graphQL的案例

wangjuntytl / 1822人閱讀

摘要:在的文檔中看到了有集成的指導,所以在本地嘗試下先用寫出一個,之后再去與集成起來。

在Nest.js的文檔中看到了有集成GraphQL的指導,所以在本地嘗試下先用Koa寫出一個DEMO,之后再去與Nest.js集成起來。

先寫出數據庫模型(這個文件是之前就存在的,沒有做更改,將文件名改成了models.ts):

/**
 * Created by w on 2018/4/13.
 */
const mongoose = require("mongoose");

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/ticket", {
  server: {
    socketOptions: {
      keepAlive: 1
    }
  }
});

const models = {
  users: {
    username: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    },
    description: {
      type: String
    },
    createTime: {
      type: Date,
      default: new Date()
    }
  },
  tickets: {
    name: {
      type: String,
      required: true
    },
    price: {
      type: Number,
      requred: true
    },
    holdTime: {   //舉辦時間
      type: Date,
      required: true
    },
    count: {    //剩余數量
      type: String,
      required: true
    },
    place:{
      type: String,
      required: true
    },
    img: {
      type: String
    },
    description: {
      type: String
    },
    publicTime: {
      type: Date,
      default: new Date()
    },
  }
};

for (let m in models) {
  mongoose.model(m, mongoose.Schema(models[m]));
}

module.exports = {
  getModules: (name) => {
    return mongoose.model(name);
  }
};

之后編寫各自模型的GraphQL查詢文件(user.ts)):

// @ts-ignore
const {
  //@ts-ignore
  graphql, GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLID, GraphQLList, GraphQLNonNull, GraphQLInt, isOutputType,
} = require("graphql");
// @ts-ignore
const User = require("../db/model").getModules("users");

const userType = new GraphQLObjectType({
  name: "User",
  fields: {
    username: {
      type: GraphQLString,
    },
    password: {
      type: GraphQLString,
    },
    description: {
      type: GraphQLString,
    },
    createTime: {
      type: GraphQLString,
    }
  }
});

module.exports = {
  query: {
    type: new GraphQLList(userType),
    args: {
      username: {
        username: "username",
        type: GraphQLNonNull(GraphQLString)
      }
    },
    resolve(root, params, options) {
      if (params.username === "$all") {
        return User.find().exec()
      }
      return User.find({ username: params.username }).exec();
    }
  },
  mutate: {
    type: new GraphQLList(userType),
    args: {
      operate: {
        name: "operate",
        type: GraphQLString
      },
      username: {
        name: "username",
        type: GraphQLNonNull(GraphQLString)
      },
      possword: {
        name: "price",
        type: GraphQLNonNull(GraphQLString)
      },
      createTime: {
        name: "createTime",
        type: GraphQLString,
      },
      description: {
        name: "description",
        type: GraphQLString
      }
    },
    resolve: async (root, params, options) => {
      try {
        if (params.operate === "$delete") {
          await User.delete({username: params.username});

          return User.find().exec()
        }
        if (params.operate === "$update") {
          await User.update({username: params.username});

          return User.find({ username: params.username }).exec()
        }
        let user = new User({
          username: params.username,
          password: params.password,
          description: params.description,
          createTime: params.createTime
        });
        await user.save();

        return user.find({ username: params.username }).exec()
      } catch (e) {
        console.error("Error while save data: ", e);
      }
    }
  }
}

ticket.ts:

// @ts-ignore
const {
  // @ts-ignore
  graphql, GraphQLSchema, GraphQLObjectType, GraphQLString, GraphQLID, GraphQLList, GraphQLNonNull, GraphQLInt, isOutputType,
} = require("graphql");
// @ts-ignore
const Ticket = require("../db/model").getModules("tickets");

const ticketType = new GraphQLObjectType({
  name: "Ticket",
  fields: {
    name: {
      type: GraphQLString
    },
    price: {
      type: GraphQLInt
    },
    holdTime: {
      type: GraphQLString
    },
    count: {
      type: GraphQLInt
    },
    place: {
      type: GraphQLString
    },
    img: {
      type: GraphQLString
    },
    description: {
      type: GraphQLString
    },
    publicTime: {
      type: GraphQLString
    }
  }
});

module.exports = {
  query: {
    type: new GraphQLList(ticketType),
    args: {
      name: {
        name: "name",
        type: GraphQLNonNull(GraphQLString)
      }
    },
    resolve(root, params, options) {
      if (params.name === "$all") {
        return Ticket.find().exec()
      }
      return Ticket.find({ name: params.name }).exec();
    }
  },
  mutate: {
    type: new GraphQLList(ticketType),
    args: {
      operate: {
        name: "operate",
        type: GraphQLString
      },
      name: {
        name: "name",
        type: GraphQLNonNull(GraphQLString)
      },
      price: {
        name: "price",
        type: GraphQLInt
      },
      holdTime: {
        name: "holdTime",
        type: GraphQLNonNull(GraphQLString)
      },
      count: {
        name: "count",
        type: GraphQLNonNull(GraphQLInt)
      },
      place: {
        name: "place",
        type: GraphQLNonNull(GraphQLString)
      },
      img: {
        name: "img",
        type: GraphQLString
      },
      description: {
        name: "description",
        type: GraphQLString
      },
      publicTime: {
        name: "publicTime",
        type: GraphQLString
      }
    },
    resolve: async (root, params, options) => {
      try {
        if (params.operate === "$delete") {
          await Ticket.findOneAndRemove({ name: params.name });

          return Ticket.find().exec();
        }
        if (params.operate === "$update") {
          await Ticket.findByIdAndUpdate({ name: params.name }, {
            name: params.name,
            price: params.price,
            holdTime: params.holdTime,
            count: params.count,
            place: params.place,
            img: params.img,
            description: params.description,
            publicTime: params.publicTime
          });

          return Ticket.find().exec();
        }
        let ticket = new Ticket({
          name: params.name,
          price: params.price,
          holdTime: params.holdTime,
          count: params.count,
          place: params.place,
          img: params.img,
          description: params.description,
          publicTime: params.publicTime
        });
        await ticket.save();

        return Ticket.find({ name: params.name }).exec()
      } catch (e) {
        console.error("Error while save data: ", e);
      }
    }
  }
}

接下來編寫用于查詢或修改數據的Schema.ts:

const {
  //@ts-ignore
  GraphQLSchema, GraphQLObjectType,
} = require("graphql");
//@ts-ignore
const Ticket = require("./ticket");
//@ts-ignore
const User = require("./user");

module.exports = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: "Queries",
    fields: {
      Ticket: Ticket.query,
      User: User.query,
    }
  }),
  mutation: new GraphQLObjectType({
    name: "Mutations",
    fields: {
      Ticket: Ticket.mutate,
      User: User.mutate,
    }
  })
})

編寫服務端(server.ts):

const Koa = require("koa");
const app = new Koa();
const koaBody = require("koa-body");
const CombileRouter = require("./combineRouter");

app
  .use(koaBody({
    multipart: true,
    formidable: {
      keepExtensions: true,
    },
  }))
  .use(CombileRouter.routes())
  .use(CombileRouter.routes());

app.listen(5000, () => {
  console.log("App running~");
})

定義ticket路由的ticket.router.ts:

const KoaRouter = require("koa-router");
const ticketRouter = new KoaRouter();
// @ts-ignore
const { graphqlKoa, graphiqlKoa } = require("graphql-server-koa");
// @ts-ignore
const Ticket = require("../db/model").getModules("tickets");
const ticketSchema = require("../graphql/schema");

ticketRouter.get("/ticket/all", async (ctx) => {
  try {
    let result = await Ticket.find({});

    ctx.body = { data: Object.assign({}, result), code: "0" };
  } catch (e) {
    console.error("Getting all ticket error: ", e);
  }
});

ticketRouter.post("/graphql", async (ctx, next) => {
  console.log("graphql", ctx.request.body);
  await graphqlKoa({schema: ticketSchema})(ctx, next)
})
.get("/graphql", async (ctx, next) => {
  await graphqlKoa({schema: ticketSchema})(ctx, next)
})
.get("/graphiql", async (ctx, next) => {
  await graphiqlKoa({endpointURL: "/graphql"})(ctx, next)
})


module.exports = ticketRouter;

還有之前定義的user.router.ts(測試這個user路由是否是reachable的):

const Router = require("koa-router");
const userRouter = new Router();
// @ts-ignore
const { graphiqlKoa } = require("graphql-server-koa");

userRouter.get("/user/all", async (ctx) => {
  ctx.body = {
    code: "0",
    msg: "OK",
    info: {
      data: [{
        username: "a",
        id: 0,
        desc: "ok",
      }, {
        username: "d",
        id: 1,
        desc: "ok",
      }, {
        username: "c",
        id: 2,
        desc: "ok",
      }, {
        username: "b",
        id: 3,
        desc: "ok",
      }]
    }
  }
});

module.exports = userRouter;

將兩個路由文件融合起來(combineRouter.ts):

const UserRouter:object = require("./koa-router/user.router");
const TicketRouter:object = require("./koa-router/ticket.router");

const combiler = (routers: object[]): object => {
  let arr = [];
  
  routers.forEach(v => {
    //@ts-ignore
    arr.push(...v.stack)
  });
  return Object.assign(routers[0], { stack:arr });
}

const res = combiler([UserRouter, TicketRouter]);

module.exports = res;

OK了,這部分就寫好了基礎的query和mutation功能,還有刪除的功能之后再加上。
附上tsconfig.json文件:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "sourceMap": true,
    "experimentalDecorators": true,
  },
  "exclude": [
    "node_modules"
  ]
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/104265.html

相關文章

  • GraphQL 搭配 Koa 最佳入門實踐

    摘要:如下圖嗯,如圖都已經查詢到我們保存的全部數據,并且全部返回前端了。如圖沒錯,什么都沒有就是查詢服務的界面。寫好了之后我們在配置一下路由,進入里面,加入下面幾行代碼。 GraphQL一種用為你 API 而生的查詢語言,2018已經到來,PWA還沒有大量投入生產應用之中就已經火起來了,GraphQL的應用或許也不會太遠了。前端的發展的最大一個特點就是變化快,有時候應對各種需求場景的變化,不...

    MoAir 評論0 收藏0
  • 編寫 Node.js Rest API 10 個最佳實踐

    摘要:要對進行黑盒測試測試的最好辦法是對他們進行黑盒測試,黑盒測試是一種不關心應用內部結構和工作原理的測試方法,測試時系統任何部分都不應該被。此外,有了黑盒測試并不意味著不需要單元測試,針對的單元測試還是需要編寫的。 本文首發于之乎專欄前端周刊,全文共 6953 字,讀完需 8 分鐘,速度需 2 分鐘。翻譯自:RingStack 的文章 https://blog.risingstack.co...

    ermaoL 評論0 收藏0
  • koa2 + graphql + typescript + jwt + typeormnodejs

    最近寫了一個node項目,主要使用到的技術有: koa2 // nodejs 框架 koa-router // koa路由 graphql // 查詢api typescript // 強類型語言 jwt // 授權 typeorm // typescript的一個orm mysql2 // 內容數據庫 mongodb // 日志存儲數據庫 redis // 服務器緩存 項目結構:sh...

    Dogee 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<