一、添加如下代碼
const middleware = (request, response, next) => {
if (request.url.indexOf('/graphql') != -1 && request.headers.cookie.indexOf('auth') == -1) {
response.send(JSON.stringify({
error: "您沒有訪問這個接口的權(quán)限"
}));
return;
}
next();
}
// 注冊中間件
app.use(middleware);
const express = require('express');
const {buildSchema} = require('graphql');
const {graphqlHTTP} = require('express-graphql');
// 定義Schema, 查詢方法和返回值類型
const schema = buildSchema(`
input AccountInput {
name: String
age: Int
sex: String
department: String
}
type Account {
name: String
age: Int
sex: String
department: String
}
type Mutation {
createAccount(input: AccountInput): Account
updateAccount(id: ID!, input: AccountInput): Account
}
// 使用Mutation時,必須要有Query
type Query {
accounts: [Account]
}
`)
const fakeDB = {};
//定義查詢對應(yīng)的處理器
const root = {
createAccount({input}) {
// 相當于數(shù)據(jù)庫保存
fakeDB[input.name] = input;
//返回保存結(jié)果
return fakeDB[input.name];
},
updateAccount({id, input}) {
// 相當于數(shù)據(jù)庫的更新
const updatedAccount = Object.assign({}, fakeDB[id], input);
fakeDB[id] = updatedAccount;
// 返回保存結(jié)果
return updatedAccount;
},
accounts() {
var arr = [];
for (const key in fakeDB) {
arr.push(fakeDB[key]);
}
return arr;
}
}
const app = express();
//添加認證權(quán)限
const middleware = (request, response, next) => {
if (request.url.indexOf('/graphql') != -1 && request.headers.cookie.indexOf('auth') == -1) {
response.send(JSON.stringify({
error: "您沒有訪問這個接口的權(quán)限"
}));
return;
}
next();
}
// 注冊中間件
app.use(middleware);
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true
}))
app.listen(3000);
image.png
image.png