说明:

  • 接第二篇文章,代码也是在第二篇文章之上
  • 本文只是针对mondodb来操作

一、添加相关的包

  • yarn add Mongoose

二、初始化Mongodb

  • 修改server.ts
  • 导入 import * as Mongoose from 'mongoose';
  • 添加了方法 mongodbInit()
  • 全部代码如下 :
    1. import * as express from 'express';
    2. const { graphqlExpress, graphiqlExpress } = require('apollo-server-express')
    3. const expressPlayground = require('graphql-playground-middleware-express').default;
    4. import * as Mongoose from 'mongoose';
    5. var bodyParser = require('body-parser');
    6.  
    7. import schema from './schema';
    8.  
    9. class Server {
    10. public app: express.Application;
    11. constructor() {
    12. this.app = express();
    13. this.routes();
    14. this.mongodbInit();
    15. }
    16.  
    17. private routes(): void {
    18. this.app.use('/graphql',bodyParser.json(), graphqlExpress({ schema }));
    19. this.app.get('/playground', expressPlayground({ endpoint: '/graphql' }));
    20. }
    21.  
    22. private mongodbInit() {
    23. const MONGO_URI = "mongodb://localhost/gqlServer";
    24. Mongoose.connect(MONGO_URI || process.env.MONGO_URI);
    25. this.app.use(bodyParser.urlencoded({ extended: false }));
    26. this.app.use(bodyParser.json());
    27. }
    28. }
    29.  
    30. export default new Server().app;

三、修改user文件

  • 添加user.ts代码如下:
    1. import { model, Schema, Document } from 'mongoose';
    2.  
    3. export interface IUserModel extends Document {
    4. id:string,
    5. name: String,
    6. password: String,
    7. }
    8.  
    9. let UserSchema: Schema = new Schema({
    10. name: String,
    11. password: String,
    12. createAt: {
    13. type: Date,
    14. default: new Date(),
    15. required: true
    16. },
    17. updateAt: {
    18. type: Date,
    19. default: new Date(),
    20. required: true
    21. },
    22. })
    23.  
    24. export default model<IUserModel>('User', UserSchema);
  • 修改resolver.ts代码如下:
    1. import UserSchema, { IUserModel } from './user';
    2.  
    3. export class User {
    4. constructor() {
    5.  
    6. }
    7.  
    8. static Query: any = {
    9. getUsers(parent, { }, context) {
    10. return UserSchema.find();
    11. }
    12. }
    13.  
    14. static Mutation: any = {
    15. saveUser(parent, { user }, context) {
    16. return UserSchema.create(user)
    17. }
    18. }
    19.  
    20. }

四、运行项目 yarn start 打开地址http://localhost:8080/playground应该可以添加用户和查找用户了效果如下:

、增删改查相关的方法可以自己去扩展

六、关联

  • 添加角色文件夹role/role.gql,role/resolve,role/resolver.ts
  • 代码基本可以复制user里面的代码改相关的名字
  • 项目结构
  • role.gql代码
    1. type Role{
    2. id:String
    3. roleName:String
    4. }
    5.  
    6. extend type Query {
    7. # 查找所有角色
    8. getRoles: [Role]
    9. }
    10.  
    11. extend type Mutation {
    12. # 创建角色| 修改角色
    13. saveRole(role:inputRole):Role
    14. }
    15.  
    16. input inputRole{
    17. id:String
    18. roleName:String
    19. }
  • role.ts代码
    1. import { model, Schema, Document } from 'mongoose';
    2.  
    3. export interface IRoleModel extends Document {
    4. id:string,
    5. roleMame: String,
    6. }
    7.  
    8. let RoleSchema: Schema = new Schema({
    9. roleMame: String,
    10. createAt: {
    11. type: Date,
    12. default: new Date(),
    13. required: true
    14. },
    15. updateAt: {
    16. type: Date,
    17. default: new Date(),
    18. required: true
    19. },
    20. })
    21.  
    22. export default model<IRoleModel>('Role', RoleSchema);
  • resolver.ts 代码
    1. import RoleSchema, { IRoleModel } from './role';
    2.  
    3. export class Role {
    4. constructor() {
    5.  
    6. }
    7.  
    8. static Query: any = {
    9. getRoles(parent, { }, context) {
    10. return RoleSchema.find();
    11. }
    12. }
    13.  
    14. static Mutation: any = {
    15. saveRole(parent, { role }, context) {
    16. return RoleSchema.create(role)
    17. }
    18. }
    19.  
    20. }
  • 导入resolver到resolvers.ts代码如下:
    1. import { User } from "./user/resolver";
    2. import { Role } from "./role/resolver";
    3.  
    4. export default {
    5. Query: {
    6. ...User.Query,
    7. ...Role.Query
    8. },
    9. Mutation: {
    10. ...User.Mutation,
    11. ...Role.Mutation
    12. },
    13. };
  • 导入role.gql 到src/schema.ts 代码如下:
    1. import { makeExecutableSchema } from 'graphql-tools';
    2. import resolver from "./resolvers";
    3. var requireText = require('require-text');
    4. var Base = requireText('./base.gql', require);
    5. var User = requireText('./user/user.gql', require);
    6. var Role = requireText('./role/role.gql', require); //添加了角色
    7.  
    8. //基础信息
    9. var typeDefs = [Base];
    10. typeDefs = typeDefs.concat(User);
    11. typeDefs = typeDefs.concat(Role);
    12.  
    13. const schema = makeExecutableSchema({
    14. typeDefs: typeDefs,
    15. resolvers: resolver
    16. })
    17.  
    18. export default schema; 
  • 运行可以看到相关表,尝试添加一个角色,和查找一下

七、关联用户与角色,基本关系,每一个用户有一个角色1对1

  • 修改文件user.gql代码如下:
    1. type User{
    2. id:String
    3. name:String
    4. passwrod:String
    5. # 添加了role字段
    6. Role:Role
    7. }
    8.  
    9. extend type Query {
    10. # 查找所有用户
    11. getUsers: [User]
    12. }
    13.  
    14. extend type Mutation {
    15. # 创建用户|修改用户
    16. saveUser(user:inputUser):User
    17. }
    18.  
    19. input inputUser{
    20. id:String
    21. name:String
    22. passwrod:String
    23. # 添加了roleid
    24. roleId:String
    25. }
  • 修改user.ts文件代码如下:
    1. import { model, Schema, Document } from 'mongoose';
    2.  
    3. export interface IUserModel extends Document {
    4. id:string,
    5. name: String,
    6. passwrod: String,
    7. roleId: String,//只是添加了这里
    8. }
    9.  
    10. let UserSchema: Schema = new Schema({
    11. name: String,
    12. passwrod: String,
    13. roleId: String, //只是添加了这里
    14. createAt: {
    15. type: Date,
    16. default: new Date(),
    17. required: true
    18. },
    19. updateAt: {
    20. type: Date,
    21. default: new Date(),
    22. required: true
    23. },
    24. })
    25.  
    26. export default model<IUserModel>('User', UserSchema);
  • 修改user/resolver.ts文件代码如下:
    1. import UserSchema, { IUserModel } from './user';
    2. import RoleSchema from '../role/role';
    3.  
    4. export class User {
    5. constructor() {
    6.  
    7. }
    8.  
    9. //只是添加用户的角色
    10. static User: any = {
    11. Role(model) {
    12. return RoleSchema.findById(model.roleId);
    13. },
    14. }
    15.  
    16. static Query: any = {
    17. getUsers(parent, { }, context) {
    18. return UserSchema.find();
    19. }
    20. }
    21.  
    22. static Mutation: any = {
    23. saveUser(parent, { user }, context) {
    24. return UserSchema.create(user)
    25. }
    26. }
    27.  
    28. }
  • 导入用户角色到resolver.ts代码如下:
    1. import { User } from "./user/resolver";
    2. import { Role } from "./role/resolver";
    3.  
    4. export default {
    5. Query: {
    6. ...User.Query,
    7. ...Role.Query
    8. },
    9. Mutation: {
    10. ...User.Mutation,
    11. ...Role.Mutation
    12. },
    13. User:User.User //只是添加了这一行
    14. };
  • 运行,添加一个角色,根据角色id添加用户,页面查询应该可以看到以下结果:

八,相关的增加修改删除分页代码参考下面代码:

  • user.gql
    1. # 系统用户表
    2. type User {
    3. id: ID!
    4. # 用户登录名
    5. username: String
    6. # 姓名
    7. name: String
    8. # 邮件
    9. email:String
    10. # 密码
    11. password:String
    12. # 创建时间
    13. createAt:Date
    14. # 修改时间
    15. updateAt:Date
    16. #用户角色
    17. Role:Role
    18. #是否有效
    19. isValid:Boolean
    20. #用户资料
    21. Profile:Profile
    22. }
    23.  
    24. extend type Query {
    25. # 查找所有用户
    26. getUsers: [User]
    27. # 根据ID查找用户
    28. getUserById(id:String):User
    29. # 分页查找
    30. getUserPage(pageIndex: Int, pageSize: Int,user:searchUser): [User]
    31. # 查找分页总数
    32. getUserCount(user:searchUser):Int
    33. # 根据条件查找
    34. getUserWhere(user:searchUser): [User]
    35. # 用户登录
    36. login (username:String!,password:String!): User
    37. # 用户退出
    38. logOut:Boolean,
    39. #当前登录用户
    40. currentUser:User
    41.  
    42. }
    43.  
    44. extend type Mutation {
    45. # 创建用户|修改用户
    46. saveUser(user:inputUser):User
    47. # 删除用户
    48. deleteUser(id:String):Boolean
    49. }
    50.  
    51. input inputUser{
    52. id:String
    53. username: String
    54. name: String
    55. email:String
    56. password:String
    57. roleId:String
    58. profileId:String
    59. isValid:Boolean
    60. }
    61.  
    62. input searchUser{
    63. username:Json
    64. roleId:Json
    65. email:Json
    66. name:Json
    67. }
  • resolver.ts
    1. import UserSchema, { IUserModel } from './user';
    2. import RoleSchema from '../role/role';
    3. import ProfileSchema from '../profile/profile';
    4.  
    5. import { DocumentQuery, MongoosePromise } from 'mongoose';
    6.  
    7. export class User {
    8.  
    9. constructor() {
    10. }
    11.  
    12. static User: any = {
    13. Role(model) {
    14. return RoleSchema.findById(model.roleId);
    15. },
    16. Profile(model) {
    17. return ProfileSchema.findOne({ userId: model.id });
    18. }
    19. }
    20.  
    21. static Query: any = {
    22. getUsers(parent, __, context): Promise<Array<IUserModel>> {
    23. //if (!context.user) return null;
    24. let promise = new Promise<Array<IUserModel>>((resolve, reject) => {
    25. UserSchema.find().then(res => {
    26. resolve(res);
    27. }).catch(err => resolve(null));
    28. });
    29. return promise;
    30. },
    31.  
    32. getUserById(parent, { id }, context): Promise<IUserModel> {
    33. //if (!context.user) return null;
    34.  
    35. let promise = new Promise<IUserModel>((resolve, reject) => {
    36. UserSchema.findById(id).then(res => {
    37. resolve(res);
    38. }).catch(err => resolve(null));
    39. });
    40. return promise;
    41. },
    42.  
    43. getUserPage(parent, { pageIndex = 1, pageSize = 10, user }, context) {
    44. //if (!context.user) return null;
    45. var skip = (pageIndex - 1) * pageSize
    46. var userInfo = UserSchema.find(user).skip(skip).limit(pageSize)
    47. return userInfo;
    48. },
    49.  
    50. getUserWhere(parent, { user }, context) {
    51. //if (!context.user) return null;
    52. console.log(user);
    53. var users = UserSchema.find(user);
    54. return users;
    55. },
    56.  
    57. getUserCount(parent, { user }, context) {
    58. //if (!context.user) return 0;
    59. var count = UserSchema.count(user);
    60. return count;
    61. },
    62.  
    63. login(parent, { username, password }, context) {
    64. return new Promise<any>((resolve, reject) => {
    65. UserSchema.find({ username, password }).then(data => {
    66. if (data.length > 0) {
    67. var user=data[0];
    68. context.session.user = user;
    69. resolve(user);
    70. } else {
    71. context.session.user = null;
    72. resolve(null);
    73. }
    74. })
    75. })
    76. },
    77. logOut(parent, { }, context) {
    78. context.user = null;
    79. context.session.user = null;
    80. return true;
    81. },
    82. currentUser(parent, { }, context) {
    83. //if (!context.user) return null;
    84. let promise = new Promise<IUserModel>((resolve, reject) => {
    85. let user = context.user;
    86. if (user) {
    87. UserSchema.findById(user._id).then(res => {
    88. resolve(res);
    89. }).catch(err => resolve(null));
    90. } else {
    91. resolve(null);
    92. }
    93. });
    94. return promise;
    95.  
    96. },
    97. }
    98.  
    99. static Mutation: any = {
    100. saveUser(parent, { user }, context) {
    101. //正式运行时请取消注释
    102. // if (!context.user) return null;
    103. if (user.id && user.id != "0") {
    104. return new Promise<IUserModel>((resolve, reject) => {
    105. UserSchema.findByIdAndUpdate(user.id, user, (err, res) => {
    106. Object.assign(res, user);
    107. resolve(res);
    108. })
    109. });
    110. }
    111. return UserSchema.create(user)
    112. },
    113.  
    114. deleteUser(parent, { id }, context): Promise<Boolean> {
    115. //if (!context.user) return null;
    116. let promise = new Promise<Boolean>((resolve, reject) => {
    117. UserSchema.findByIdAndRemove(id, (err, res) => {
    118. resolve(res != null)
    119. }).catch(err => reject(err));
    120. });
    121. return promise;
    122. }
    123. }
    124. }

graphql 数据增删改查分页及关联操作(三)的更多相关文章

  1. IOS-CoreData(增删改查、表关联、分页和模糊查询、多个数据库)

    1>什么是CoreData Core Data是iOS5之后才出现的一个框架,它提供了对象-关系映射(ORM)的功能,即能够将OC对象转化成数据,保存在SQLite数据库文件中,也能够将保存在数 ...

  2. OracleHelper(对增删改查分页查询操作进行了面向对象的封装,对批量增删改操作的事务封装)

    公司的一个新项目使用ASP.NET MVC开发,经理让我写个OracleHelper,我从网上找了一个比较全的OracleHelper类,缺点是查询的时候返回DataSet,数据增删改要写很多代码(当 ...

  3. salesforce 零基础开发入门学习(六)简单的数据增删改查页面的构建

    VisualForce封装了很多的标签用来进行页面设计,本篇主要讲述简单的页面增删改查.使用的内容和设计到前台页面使用的标签相对简单,如果需要深入了解VF相关知识以及标签, 可以通过以下链接查看或下载 ...

  4. node-express项目的搭建并通过mongoose操作MongoDB实现增删改查分页排序(四)

    最近写了一个用node来操作MongoDB完成增.删.改.查.排序.分页功能的示例,并且已经放在了服务器上地址:http://39.105.32.180:3333. Mongoose是在node.js ...

  5. 【转载】salesforce 零基础开发入门学习(六)简单的数据增删改查页面的构建

    salesforce 零基础开发入门学习(六)简单的数据增删改查页面的构建   VisualForce封装了很多的标签用来进行页面设计,本篇主要讲述简单的页面增删改查.使用的内容和设计到前台页面使用的 ...

  6. C#操作Excel数据增删改查(转)

    C#操作Excel数据增删改查. 首先创建ExcelDB.xlsx文件,并添加两张工作表. 工作表1: UserInfo表,字段:UserId.UserName.Age.Address.CreateT ...

  7. C#操作Excel数据增删改查示例

    Excel数据增删改查我们可以使用c#进行操作,首先创建ExcelDB.xlsx文件,并添加两张工作表,接下按照下面的操作步骤即可 C#操作Excel数据增删改查. 首先创建ExcelDB.xlsx文 ...

  8. SpringMVC4+MyBatis3+SQLServer 2014 整合(包括增删改查分页)

    前言 说起整合自然离开ssm,我本身并不太喜欢ORM,尤其是MyBatis,把SQL语句写在xml里,尤其是大SQL,可读性不高,出错也不容易排查. 开发环境 idea2016.SpringMVC4. ...

  9. C#在winform中操作数据库,实现数据增删改查

    1.前言: 运行环境:VS2013+SQL2008+Windows10 程序界面预览: 使用的主要控件:dataGridview和menuStrip等. 2.功能具体介绍: 1.首先,我们要先实现基本 ...

随机推荐

  1. UVA11082 行列模型

    行列二分图模型,行指向列即表示权重w[i][j] 避免零流的方法就是使下界为1 #include<bits/stdc++.h> #define rep(i,j,k) for(int i = ...

  2. android 快速开发框架

    https://github.com/lipanquan/LPQRapidDevelopmentFramework 依赖LPQLibrary https://github.com/lipanquan/ ...

  3. WPF Canvas转换为位图 (RenderTargetBitmap)

    使用 RenderTargetBitmap 的注意事项: 1. 要渲染的Canvas元素要放在Border元素内,并且此Border元素不能设置边框宽度(BorderThickness),不然生成的位 ...

  4. C语言变参函数的实现原理

    1. 变参函数简单示例 #include <stdarg.h> #include <stdio.h> int Accumlate(int nr, ...) { ; ; va_l ...

  5. 一行CMD命令kill(杀)掉你的进程

    查看进程 pi@raspberry:~ $ ps -ef | grep python3 UID PID PPID C STIME TTY TIME CMD pi 4678 4666 0 11:57 p ...

  6. ECharts基本设置

    theme = { // 全图默认背景 // backgroundColor: ‘rgba(0,0,0,0)’, // 默认色板 color: ['#ff7f50','#87cefa','#da70d ...

  7. CESM部署安装环境和使用

    平台信息 Description: CentOS Linux release 7.6.1810 (Core) 安装CESM 安装前提:(小提示:耗时较长,需要耐心)阅读原文 CentOS 7(检查:s ...

  8. JS 获取get请求方式的参数

    //获取页面中的参数    name值参数名称(例如:http://localhost:8099/index.aspx?id=10,name则指的是id)function GetQueryString ...

  9. maya 安装不上

    AUTODESK系列软件着实令人头疼,安装失败之后不能完全卸载!!!(比如maya,cad,3dsmax等).有时手动删除注册表重装之后还是会出现各种问题,每个版本的C++Runtime和.NET f ...

  10. 查询pthread库的函数

    首先需要先安装pthread看的手册文档,然后用如下命令查询: man -k pthread