name: Graphql設計 slug: graphql-design version: 1.0.0 displayName: Graphql設計 description: > Graphql設計專用技能,幫助AI Agent高效完成相關任務。 summary: "Graphql設計專用技能,幫助AI Agent高效完成相關任務。" license: MIT category: 開發者工具 framework: - Claude Code - Codex - Hermes Agent - OpenClaw - QClaw - WorkBuddy platform: multi-platform homepage: "https://github.com/1991513ccie-png" repository: "https://github.com/1991513ccie-png"
type Query { user(id: ID!): User users(filter: UserFilter, first: Int = 20, after: String): UserConnection! } type Mutation { createUser(input: CreateUserInput!): CreateUserPayload! updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload! } type Subscription { orderStatusChanged(orderId: ID!): Order! } type User { id: ID! email: String! name: String! orders(first: Int = 10, after: String): OrderConnection! createdAt: DateTime! } input CreateUserInput { email: String! name: String! } type CreateUserPayload { user: User errors: [UserError!]! } type UserError { field: String! message: String! } type UserConnection { edges: [UserEdge!]! pageInfo: PageInfo! totalCount: Int! } type UserEdge { node: User! cursor: String! } type PageInfo { hasNextPage: Boolean! endCursor: String }發現更多技能外掛,請訪問7w4.net。
Use Relay-style connections for pagination. Return payload types from mutations with both result and errors.
const resolvers: Resolvers = {
Query: {
user: async (_, { id }, ctx) => {
return ctx.dataloaders.user.load(id);
},
users: async (_, { filter, first, after }, ctx) => {
const cursor = after ? decodeCursor(after) : undefined;
const users = await ctx.db.user.findMany({
where: buildFilter(filter),
take: first + 1,
cursor: cursor ? { id: cursor } : undefined,
orderBy: { createdAt: "desc" },
});
const hasNextPage = users.length > first;
const edges = users.slice(0, first).map(user => ({
node: user,
cursor: encodeCursor(user.id),
}));
return {
edges,
pageInfo: {
hasNextPage,
endCursor: edges[edges.length - 1]?.cursor ?? null,
},
};
},
},
Mutation: {
createUser: async (_, { input }, ctx) => {
const existing = await ctx.db.user.findUnique({ where: { email: input.email } });
if (existing) {
return { user: null, errors: [{ field: "email", message: "Already taken" }] };
}
const user = await ctx.db.user.create({ data: input });
return { user, errors: [] };
},
},
User: {
orders: async (parent, { first, after }, ctx) => {
return ctx.dataloaders.userOrders.load({ userId: parent.id, first, after });
},
},
};
import DataLoader from "dataloader";
function createLoaders(db: Database) {
return {
user: new DataLoader<string, User>(async (ids) => {
const users = await db.user.findMany({ where: { id: { in: [...ids] } } });
const userMap = new Map(users.map(u => [u.id, u]));
return ids.map(id => userMap.get(id) ?? new Error(`User ${id} not found`));
}),
userOrders: new DataLoader<{ userId: string }, Order[]>(async (keys) => {
const userIds = keys.map(k => k.userId);
const orders = await db.order.findMany({
where: { userId: { in: userIds } },
orderBy: { createdAt: "desc" },
});
const grouped = new Map<string, Order[]>();
orders.forEach(o => {
const list = grouped.get(o.userId) ?? [];
list.push(o);
grouped.set(o.userId, list);
});
return keys.map(k => grouped.get(k.userId) ?? []);
}),
};
}
Create new DataLoader instances per request to avoid stale cache across users.
const pubsub = new PubSub();
const resolvers = {
Subscription: {
orderStatusChanged: {
subscribe: (_, { orderId }) => {
return pubsub.asyncIterableIterator(`ORDER_STATUS_${orderId}`);
},
},
},
Mutation: {
updateOrderStatus: async (_, { id, status }, ctx) => {
const order = await ctx.db.order.update({ where: { id }, data: { status } });
await pubsub.publish(`ORDER_STATUS_${id}`, { orderStatusChanged: order });
return { order, errors: [] };
},
},
};
質量良好,涵蓋GraphQL設計的核心知識點。優點是提供了可直接參考的程式碼示例和常見錯誤規避建議,程式碼實用性強。不足之處是內容相對基礎,缺少實踐指導說明,深度有待提升。總體而言這是一個適合入門和參考的GraphQL設計技能。