鍓嶄竴绡囨枃绔犱粙缁嶄簡鍙樻洿鎿嶄綔锛屽湪鍒涘缓 User 瀵硅薄鐨勬椂鍊欙紝鍙紶閫掍簡 name 鍜?email 鍙傛暟锛屼絾鏄鏋滃睘鎬уお澶氭垨鑰呭垱寤哄璞$殑鏃跺€欏彧闇€瑕侀儴鍒嗗繀閫夊弬鏁帮紝鐩存帴鎶婂睘鎬ч兘褰撴垚鍙傛暟灏变笉鍚堥€備簡锛岃繖閲?GraphQL 鎻愪緵浜?Input Type 鍙傛暟鏉ヨВ鍐宠繖涓棶棰樸€備笅闈㈢湅涓緥瀛愩€?/p>
鍒涘缓 Node.js 鐨勫伐绋?/h2>
mkdir myapp
cd myapp
npm init (涓€璺洖杞?
瀹夎渚濊禆鍖?/h2>
npm install @apollo/server graphql
瀹氫箟 Schema
mkdir myapp
cd myapp
npm init (涓€璺洖杞?
npm install @apollo/server graphql
瀹氫箟 Schema
鍒涘缓 schema.graphql 鏂囦欢锛屽唴瀹瑰涓嬶細
type User {
id: ID!
name: String!
email: String!
}
type Query {
users: [User],
}
input UserInput {
name: String!
email: String!
}
type Mutation {
createUser(user: UserInput!) : User!
}
schema {
query: Query
mutation: Mutation
}
schema 鏂囦欢涓昏鍖呮嫭锛?/p>
- 鏂板浜嗚緭鍏ュ弬鏁?UserInput 鐨勫畾涔夛紝浣滀负婕旂ず鍙寘鍚袱涓弬鏁?name 鍜?email銆?/li>
- 淇敼鍙樻洿鎿嶄綔涓嶅啀浣跨敤 name 鍜?email 浣滀负鍙傛暟锛岃€屾槸鏀规垚浣跨敤杈撳叆鍙傛暟 UserInput銆?/li>
瀹炵幇澶勭悊鍣?/h2>
鍒涘缓 resolvers.js 鏂囦欢锛屽唴瀹瑰涓嬶細
const user1 = {id: 1, name: 'user1', email: 'user1@gmail.com'};
const user2 = {id: 2, name: 'user2', email: 'user2@gmail.com'};
const user3 = {id: 3, name: 'user3', email: 'user3@gmail.com'};
const users = [user1, user2, user3];
const resolvers = {
Query: {
users: () => users,
},
Mutation: {
createUser(obj, args, context, info) {
let user = {id: users.length + 1,name: args.user.name, email: args.user.email};
users.push(user);
return user;
}
}
};
module.exports = resolvers;
澶勭悊鍣ㄥ嚱鏁版湁浜涘彉鍖栵紝涓昏灏辨槸 args 閲屼笉鐩存帴浣跨敤 name 鍜?email 灞炴€э紝鑰屾槸閫氳繃 args 涓殑 user 瀵硅薄鏉ラ棿鎺ヤ娇鐢ㄣ€?/p>
涓荤▼搴?/h2>
鍒涘缓 server.js 鏂囦欢锛屽唴瀹瑰涓嬶細
const { ApolloServer } = require('@apollo/server');
const { startStandaloneServer } = require('@apollo/server/standalone');
const fs = require("fs");
const typeDefs = fs.readFileSync('./schema.graphql').toString();
const resolvers = require('./resolvers');
const server = new ApolloServer({
typeDefs,
resolvers,
});
startStandaloneServer(server).then(function(data) {
console.log(`馃殌 Server ready at ${data.url}`);
});
娴嬭瘯
鍚姩鏈嶅姟
node server.js
鏈嶅姟鍚姩鍚庯紝璁块棶 http://localhost:4000 杩涜娴嬭瘯銆?/p>
鍙樻洿鎿嶄綔
鍙樻洿璇锋眰
mutation createUser($user: UserInput!) {
createUser(user: $user) {
id,
name,
email
}
}
鍙樻洿鍙傛暟
{
"user": {
"name": "newuser",
"email": "newuser@gmail.com"
}
}
鎿嶄綔缁撴灉
{
"data": {
"createUser": {
"id": "4",
"name": "newuser",
"email": "newuser@gmail.com"
}
}
}