apollo/server express,mongoose,resolver chains

apollo/server Get started with Apollo Server - Apollo GraphQL Docs

mongoose Mongoose 5.0 中文文档

index2.ts

import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import express from 'express';
import http from 'http';
import cors from 'cors';
import { typeDefs, resolvers } from './index2-schema';
import { users } from "./index2-mongoose";

const app = express();

const httpServer = http.createServer(app);

const server = new ApolloServer<{ token?: String }>({
  typeDefs,
  resolvers,
  plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
});

server.start().then(() => {
  app.use(
    '/graphql',
    cors<cors.CorsRequest>(),
    express.json(),
    expressMiddleware(server, {
      context: async ({ req }) => ({
        token: req.headers.token,
        msg: "会传递到所有的resolver context参数中",
        dataSources: { users }
      }),
    }),
  );

  httpServer.listen(4000, () => {
    console.log(`🚀 Server ready at http://localhost:4000/graphql`);
  });
});

index2-schema.ts

import { users } from "./index2-mongoose";

export let typeDefs = `#graphql
  #1
  type Event {
    name: String!
    date: String!
    location: Location
  }
  
  type Location {
    name: String!
    weather: WeatherInfo
  }
  
  type WeatherInfo {
    temperature: Float
    description: String
  }

  #2
  type Library {
    branch: String!
    books: [Book]
  }

  type Book {
    title: String
    author: Author
  }

  type Author {
    name: String!
  }

  #3
  type User{
    _id: ID!
    name: String!
    age: Int!
    sex: String!
  }

  type Query {
    books: [Book]
    users: [User]
    user(id: ID!): User
    upcomingEvents: [Event!]!
    libraries: [Library]
    Library: Library
  }
`;

export const resolvers = {
  Query: {
    books() {
      return [
        { id: '1', title: "t1", },
        { id: '2', title: "t2", },
      ]
    },
    async users(parent: any, args: any, context: { dataSources: { users: { find: () => any; }; }; }) {
      let value = await users.find();
      console.log(await context.dataSources.users.find());
      return value;
    },
    async user(parent: any, { id }: any, context: { dataSources: { users: { findById: (arg0: any) => any; }; }; }) {
      console.log(await context.dataSources.users.findById(id));
      const user = await users.findById(id)
      return user;
    },
    upcomingEvents() {
      return [
        {
          name: "01",
          date: "2024-1-1",
          location: {
            name: "sunday",
            weather: {
              temperature: 18.5,
              description: 'cold'
            }
          }
        }
      ];
    },
    libraries() {
      return [
        { id: "1", branch: 'downtown' },
        { id: "2", branch: 'riverside' },
      ];
    }
  },
  Library: {
    books(parent: any) {
      // parent上一步libraries解析的结果
      console.log('books parent =', parent);
      let books = [
        { id: '1', belongto: "1", title: "t1", },
        { id: '2', belongto: "1", title: "t2", },
        { id: '3', belongto: "1", title: "t2", },
        { id: '4', belongto: "2", title: "t2", },
        { id: '5', belongto: "2", title: "t2", },
      ]
      return books.filter(item => item.belongto === parent.id);
    }
  },
  Book: {
    author(parent: any, args: any, context: any, info: any) {
      // 上一步books的解析结果
      console.log(parent);
      console.log(context);
      let authors = [
        { id: '1', bid: '1', name: "Tom" },
        { id: '2', bid: '2', name: "Sam" },
        { id: '3', bid: '3', name: "Jack" },
        { id: '4', bid: '4', name: "Lucy" },
        { id: '5', bid: '5', name: "David" },
      ]
      return authors.find(item => item.bid === parent.id);
    }
  }
};

/*
// 查询案例
query ExampleQuery {
  books {
    title
    author{
      name
    }
  }
  user(id: "63ca47df3dd42947e4cc021b") {
    _id
    name
    age
  }
  upcomingEvents{
    name
  }
  libraries {
    branch
    books{
      title
      author {
        name
      }
    }
  }
}
*/

index2-mongoose.ts 

import mongoose, { Mongoose } from 'mongoose';

mongoose.set("strictQuery", true);

mongoose.connect('mongodb://localhost:27017/test');

export var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function () {
  console.log('mongodb connection success!');
});


function UserModel(mongoose: Mongoose) {
  let user = new mongoose.Schema({
    name: { type: String, required: true },

    password: { type: String, required: true },

    age: { type: Number, require: true },

    sex: { type: String, require: true },

    phone: { type: String, require: true },

    email: { type: String, required: true },

    image: { type: String, default: null },

    myChannel: { type: String, default: null },

    describle: { type: String, default: null },

    subscribeCount: { type: Number, default: 0 },
  });

  return mongoose.model("User", user);
}

export const users = UserModel(mongoose);

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值