apollo/server express,mongoose,resolver chains

2024-04-30 18:44

本文主要是介绍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#1type Event {name: String!date: String!location: Location}type Location {name: String!weather: WeatherInfo}type WeatherInfo {temperature: Floatdescription: String}#2type Library {branch: String!books: [Book]}type Book {title: Stringauthor: Author}type Author {name: String!}#3type User{_id: ID!name: String!age: Int!sex: String!}type Query {books: [Book]users: [User]user(id: ID!): UserupcomingEvents: [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 {titleauthor{name}}user(id: "63ca47df3dd42947e4cc021b") {_idnameage}upcomingEvents{name}libraries {branchbooks{titleauthor {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);

这篇关于apollo/server express,mongoose,resolver chains的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/949636

相关文章

SQL Server使用SELECT INTO实现表备份的代码示例

《SQLServer使用SELECTINTO实现表备份的代码示例》在数据库管理过程中,有时我们需要对表进行备份,以防数据丢失或修改错误,在SQLServer中,可以使用SELECTINT... 在数据库管理过程中,有时我们需要对表进行备份,以防数据丢失或修改错误。在 SQL Server 中,可以使用 SE

Window Server创建2台服务器的故障转移群集的图文教程

《WindowServer创建2台服务器的故障转移群集的图文教程》本文主要介绍了在WindowsServer系统上创建一个包含两台成员服务器的故障转移群集,文中通过图文示例介绍的非常详细,对大家的... 目录一、 准备条件二、在ServerB安装故障转移群集三、在ServerC安装故障转移群集,操作与Ser

SQL Server数据库磁盘满了的解决办法

《SQLServer数据库磁盘满了的解决办法》系统再正常运行,我还在操作中,突然发现接口报错,后续所有接口都报错了,一查日志发现说是数据库磁盘满了,所以本文记录了SQLServer数据库磁盘满了的解... 目录问题解决方法删除数据库日志设置数据库日志大小问题今http://www.chinasem.cn天发

red5-server源码

red5-server源码:https://github.com/Red5/red5-server

安装SQL2005后SQL Server Management Studio 没有出来的解决方案

一种情况,在安装 sqlServer2005 时 居然出现两个警告: 1 Com+ 目录要求 2 Edition change check 郁闷!网上说出现两个警告,是肯定装不成功的!我抱着侥幸的态度试了下,成功了。 安装成功后,正准备 “ 仅工具、联机丛书和示例(T)” 但是安装不了,他提示我“工作站组件”安装过了对现有组件无法更新或升级。 解决办法: 1 打开“控

解析apollo纵向控制标定表程序

百度apollo采用标定表描述车辆速度、加速度与油门/刹车之间的关系。该表可使无人车根据当前车速与期望加速度得到合适的油门/刹车开合度。除了文献《Baidu Apollo Auto-Calibration System - An Industry-Level Data-Driven and Learning based Vehicle Longitude Dynamic Calibrating

ERROR 2003 (HY000): Can't connect to MySQL server on (10061)

在linux系统上装了一个mysql-5.5,启动后本机都是可以访问的,操作都正常,同时建了一个%的用户(支持远程访问), root@debian:/# mysql -u loongson -pEnter password: Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id

Oracle和Sql_Server 部分sql语句的区别

比如:A表中, 字段:gxmlflag  number;  比如数据:20210115 字段:gxmldate date ;    比如数据:2021-01-15 09:50:50 一、在Oracle数据库中: 1、insert 和 update 语句: t.gxmlflag = to_char(sysdate,'yyyymmdd'),t.gxmldate=sysdate 比如:update f

Nodejs的Express框架使用总结

初始安装express,你也可以通过编辑器的shell安装依赖,比如vs # 创建并切换到 myapp 目录mkdir myappcd myapp# 初始化 package.json 文件npm init -y# 安装 express 到项目中npm i express 新建一个基础的接口 // 0. 加载 Expressconst express = require('expre

【VueJS】live-server 快速搭建服务 及 注意事项

本地开发常常需要搭建临时的服务,第一时间我们会想到用 http-server。 但现在流行修改文件浏览器自动刷新,这里可以使用 live-server 很简单就能启动一个看起来很专业的本地服务。 你只需要全局安装live-server: npm install -g live-server 并在项目根目录执行这条命令: PS E:\AblazeProject\Vue> live-serv