注册中间件和添加认证权限

一、添加如下代码

const middleware = (request, response, next) => {
if (request.url.indexOf('/graphql') != -1 && request.headers.cookie.indexOf('auth') == -1) {
response.send(JSON.stringify({
error: "您没有访问这个接口的权限"
}));
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 = {};

//定义查询对应的处理器
const root = {
   createAccount({input}) {
        // 相当于数据库保存
        fakeDB[input.name] = input;
        //返回保存结果
        return fakeDB[input.name];
    },
    updateAccount({id, input}) {
      // 相当于数据库的更新
      const updatedAccount = Object.assign({}, fakeDB[id], input);
      fakeDB[id] = updatedAccount;
      // 返回保存结果
      return updatedAccount;
    },
    accounts() {
        var arr = [];
        for (const key in fakeDB) {
            arr.push(fakeDB[key]);
        }
        return arr; 
    }
}

const app = express();

//添加认证权限
const middleware = (request, response, next) => {
    if (request.url.indexOf('/graphql') != -1 && request.headers.cookie.indexOf('auth') == -1) {
        response.send(JSON.stringify({
            error: "您没有访问这个接口的权限"
        }));
        return;
    }
    next();
}

// 注册中间件
app.use(middleware);

app.use('/graphql', graphqlHTTP({
    schema: schema,
    rootValue: root,
    graphiql: true
}))


app.listen(3000);
image.png

image.png

你可能感兴趣的:(注册中间件和添加认证权限)