我是靠谱客的博主 孤独花卷,这篇文章主要介绍graphql 数据增删改查分页及关联操作(三),现在分享给大家,希望可以做个参考。

说明:

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

一、添加相关的包

  • yarn add Mongoose

二、初始化Mongodb

  • 修改server.ts
  • 导入 import * as Mongoose from 'mongoose';
  • 添加了方法 mongodbInit()
  • 全部代码如下 :
  • 复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    import UserSchema, { IUserModel } from './user'; export class User { constructor() { } static Query: any = { getUsers(parent, { }, context) { return UserSchema.find(); } } static Mutation: any = { saveUser(parent, { user }, context) { return UserSchema.create(user) } } }

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

 

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

六、关联

  • 添加角色文件夹role/role.gql,role/resolve,role/resolver.ts
  • 代码基本可以复制user里面的代码改相关的名字
  • 项目结构
  • role.gql代码
  • 复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    1 type Role{ 2 id:String 3 roleName:String 4 } 5 6 7 extend type Query { 8 # 查找所有角色 9 getRoles: [Role] 10 } 11 12 extend type Mutation { 13 # 创建角色| 修改角色 14 saveRole(role:inputRole):Role 15 } 16 17 input inputRole{ 18 id:String 19 roleName:String 20 }
  • role.ts代码
  • 复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    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 //基础信息 10 var typeDefs = [Base]; 11 typeDefs = typeDefs.concat(User); 12 typeDefs = typeDefs.concat(Role); 13 14 const schema = makeExecutableSchema({ 15 typeDefs: typeDefs, 16 resolvers: resolver 17 }) 18 19 20 export default schema; 
  • 运行可以看到相关表,尝试添加一个角色,和查找一下

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

  • 修改文件user.gql代码如下:
  • 复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    1 type User{ 2 id:String 3 name:String 4 passwrod:String 5 # 添加了role字段 6 Role:Role 7 } 8 9 10 extend type Query { 11 # 查找所有用户 12 getUsers: [User] 13 } 14 15 extend type Mutation { 16 # 创建用户|修改用户 17 saveUser(user:inputUser):User 18 } 19 20 input inputUser{ 21 id:String 22 name:String 23 passwrod:String 24 # 添加了roleid 25 roleId:String 26 }
  • 修改user.ts文件代码如下:
  • 复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    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
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    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 }
    View Code
  • resolver.ts
    复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    1 import UserSchema, { IUserModel } from './user'; 2 import RoleSchema from '../role/role'; 3 import ProfileSchema from '../profile/profile'; 4 5 6 import { DocumentQuery, MongoosePromise } from 'mongoose'; 7 8 export class User { 9 10 11 constructor() { 12 } 13 14 static User: any = { 15 Role(model) { 16 return RoleSchema.findById(model.roleId); 17 }, 18 Profile(model) { 19 return ProfileSchema.findOne({ userId: model.id }); 20 } 21 } 22 23 static Query: any = { 24 getUsers(parent, __, context): Promise<Array<IUserModel>> { 25 //if (!context.user) return null; 26 let promise = new Promise<Array<IUserModel>>((resolve, reject) => { 27 UserSchema.find().then(res => { 28 resolve(res); 29 }).catch(err => resolve(null)); 30 }); 31 return promise; 32 }, 33 34 getUserById(parent, { id }, context): Promise<IUserModel> { 35 //if (!context.user) return null; 36 37 let promise = new Promise<IUserModel>((resolve, reject) => { 38 UserSchema.findById(id).then(res => { 39 resolve(res); 40 }).catch(err => resolve(null)); 41 }); 42 return promise; 43 }, 44 45 getUserPage(parent, { pageIndex = 1, pageSize = 10, user }, context) { 46 //if (!context.user) return null; 47 var skip = (pageIndex - 1) * pageSize 48 var userInfo = UserSchema.find(user).skip(skip).limit(pageSize) 49 return userInfo; 50 }, 51 52 getUserWhere(parent, { user }, context) { 53 //if (!context.user) return null; 54 console.log(user); 55 var users = UserSchema.find(user); 56 return users; 57 }, 58 59 getUserCount(parent, { user }, context) { 60 //if (!context.user) return 0; 61 var count = UserSchema.count(user); 62 return count; 63 }, 64 65 login(parent, { username, password }, context) { 66 return new Promise<any>((resolve, reject) => { 67 UserSchema.find({ username, password }).then(data => { 68 if (data.length > 0) { 69 var user=data[0]; 70 context.session.user = user; 71 resolve(user); 72 } else { 73 context.session.user = null; 74 resolve(null); 75 } 76 }) 77 }) 78 }, 79 logOut(parent, { }, context) { 80 context.user = null; 81 context.session.user = null; 82 return true; 83 }, 84 currentUser(parent, { }, context) { 85 //if (!context.user) return null; 86 let promise = new Promise<IUserModel>((resolve, reject) => { 87 let user = context.user; 88 if (user) { 89 UserSchema.findById(user._id).then(res => { 90 resolve(res); 91 }).catch(err => resolve(null)); 92 } else { 93 resolve(null); 94 } 95 }); 96 return promise; 97 98 }, 99 } 100 101 static Mutation: any = { 102 saveUser(parent, { user }, context) { 103 //正式运行时请取消注释 104 // if (!context.user) return null; 105 if (user.id && user.id != "0") { 106 return new Promise<IUserModel>((resolve, reject) => { 107 UserSchema.findByIdAndUpdate(user.id, user, (err, res) => { 108 Object.assign(res, user); 109 resolve(res); 110 }) 111 }); 112 } 113 return UserSchema.create(user) 114 }, 115 116 deleteUser(parent, { id }, context): Promise<Boolean> { 117 //if (!context.user) return null; 118 let promise = new Promise<Boolean>((resolve, reject) => { 119 UserSchema.findByIdAndRemove(id, (err, res) => { 120 resolve(res != null) 121 }).catch(err => reject(err)); 122 }); 123 return promise; 124 } 125 } 126 }
    View Code

     

 

转载于:https://www.cnblogs.com/lslgg/p/8178700.html

最后

以上就是孤独花卷最近收集整理的关于graphql 数据增删改查分页及关联操作(三)的全部内容,更多相关graphql内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部