摘要:在的文檔中看到了有集成的指導,所以在本地嘗試下先用寫出一個,之后再去與集成起來。
在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一種用為你 API 而生的查詢語言,2018已經到來,PWA還沒有大量投入生產應用之中就已經火起來了,GraphQL的應用或許也不會太遠了。前端的發展的最大一個特點就是變化快,有時候應對各種需求場景的變化,不...
摘要:要對進行黑盒測試測試的最好辦法是對他們進行黑盒測試,黑盒測試是一種不關心應用內部結構和工作原理的測試方法,測試時系統任何部分都不應該被。此外,有了黑盒測試并不意味著不需要單元測試,針對的單元測試還是需要編寫的。 本文首發于之乎專欄前端周刊,全文共 6953 字,讀完需 8 分鐘,速度需 2 分鐘。翻譯自:RingStack 的文章 https://blog.risingstack.co...
最近寫了一個node項目,主要使用到的技術有: koa2 // nodejs 框架 koa-router // koa路由 graphql // 查詢api typescript // 強類型語言 jwt // 授權 typeorm // typescript的一個orm mysql2 // 內容數據庫 mongodb // 日志存儲數據庫 redis // 服務器緩存 項目結構:sh...
閱讀 658·2021-11-23 09:51
閱讀 3258·2021-10-11 10:58
閱讀 15407·2021-09-29 09:47
閱讀 3528·2021-09-01 11:42
閱讀 1281·2019-08-29 16:43
閱讀 1832·2019-08-29 15:37
閱讀 2089·2019-08-29 12:56
閱讀 1718·2019-08-28 18:21