GraphQL 与数据库无关,因此您可以使用通常用于与数据库交互的任何内容,并使用查询或突变的 resolve 方法调用您定义的函数,该函数将获取/添加某些内容到数据库。
无中继
这是一个使用基于 promise 的 Knex SQL query builder 的突变示例,首先没有 Relay 来感受一下这个概念。我将假设您已经在 GraphQL 架构中创建了一个 userType,它具有三个字段:id、username 和 created:都是必需的,并且您已经定义了一个 getUser 函数用于查询数据库并返回一个用户对象。在数据库中,我也有一个 password 列,但由于我不想被查询,所以我将其从 userType 中删除。
// db.js
// take a user object and use knex to add it to the database, then return the newly
// created user from the db.
const addUser = (user) => (
knex('users')
.returning('id') // returns [id]
.insert({
username: user.username,
password: yourPasswordHashFunction(user.password),
created: Math.floor(Date.now() / 1000), // Unix time in seconds
})
.then((id) => (getUser(id[0])))
.catch((error) => (
console.log(error)
))
);
// schema.js
// the resolve function receives the query inputs as args, then you can call
// your addUser function using them
const mutationType = new GraphQLObjectType({
name: 'Mutation',
description: 'Functions to add things to the database.',
fields: () => ({
addUser: {
type: userType,
args: {
username: {
type: new GraphQLNonNull(GraphQLString),
},
password: {
type: new GraphQLNonNull(GraphQLString),
},
},
resolve: (_, args) => (
addUser({
username: args.username,
password: args.password,
})
),
},
}),
});
由于 Postgres 为我创建了 id 并且我计算了 created 时间戳,所以我的变异查询中不需要它们。
中继方式
使用graphql-relay 中的助手并非常接近Relay Starter Kit 对我很有帮助,因为一次可以吸收很多东西。 Relay 要求您以特定方式设置架构,以便它能够正常工作,但想法是相同的:在解析方法中使用您的函数从数据库中获取或添加到数据库。
一个重要的警告是,中继方式期望从getUser 返回的对象是User 类的实例,因此您必须修改getUser 以适应这种情况。
最后一个使用 Relay 的例子(fromGlobalId、globalIdField、mutationWithClientMutationId、nodeDefinitions 都来自graphql-relay):
/**
* We get the node interface and field from the Relay library.
*
* The first method defines the way we resolve an ID to its object.
* The second defines the way we resolve an object to its GraphQL type.
*
* All your types will implement this nodeInterface
*/
const { nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
const { type, id } = fromGlobalId(globalId);
if (type === 'User') {
return getUser(id);
}
return null;
},
(obj) => {
if (obj instanceof User) {
return userType;
}
return null;
}
);
// a globalId is just a base64 encoding of the database id and the type
const userType = new GraphQLObjectType({
name: 'User',
description: 'A user.',
fields: () => ({
id: globalIdField('User'),
username: {
type: new GraphQLNonNull(GraphQLString),
description: 'The username the user has selected.',
},
created: {
type: GraphQLInt,
description: 'The Unix timestamp in seconds of when the user was created.',
},
}),
interfaces: [nodeInterface],
});
// The "payload" is the data that will be returned from the mutation
const userMutation = mutationWithClientMutationId({
name: 'AddUser',
inputFields: {
username: {
type: GraphQLString,
},
password: {
type: new GraphQLNonNull(GraphQLString),
},
},
outputFields: {
user: {
type: userType,
resolve: (payload) => getUser(payload.userId),
},
},
mutateAndGetPayload: ({ username, password }) =>
addUser(
{ username, password }
).then((user) => ({ userId: user.id })), // passed to resolve in outputFields
});
const mutationType = new GraphQLObjectType({
name: 'Mutation',
description: 'Functions to add things to the database.',
fields: () => ({
addUser: userMutation,
}),
});
const queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
node: nodeField,
user: {
type: userType,
args: {
id: {
description: 'ID number of the user.',
type: new GraphQLNonNull(GraphQLID),
},
},
resolve: (root, args) => getUser(args.id),
},
}),
});