yarn add express graphql
yarn add -D @types/express @types/node @graphql-yoga/node npm-run-all rimraf ts-node-dev typescript
import express from "express";
import { createServer } from "@graphql-yoga/node";
import resolvers from "./resolver";
import fs from "fs";
import path from "path";
const app = express();
const PORT = 8000;
// ポイント1
const server = createServer({
schema: {
typeDefs: fs.readFileSync(path.join(__dirname, "schema.graphql"), "utf-8"),
resolvers,
},
graphiql: true,
});
app.use("/graphql", server);
try {
app.listen(PORT, () => {
console.log(
`Running a GraphQL API server at http://localhost:${PORT}/graphql`
);
});
} catch (e) {
if (e instanceof Error) {
console.error(e.message);
}
}
"GraphQLスキーマの定義"
// ポイント2
type Query {
info: String!
feed: [Link]!
}
type Mutation {
post(url: String!, description: String!): Link!
}
type Link {
id: ID!
description: String!
url: String!
}
// ダミーデータ
let links = [
{
id: "link-0",
description: "aaa",
url: "www.aaa.com",
},
];
// ポイント3
const resolvers = {
Query: {
info: () => "HackerNewsクローン",
feed: () => links,
},
Mutation: {
// ポイント4
post: (_parent: any, args: { description: string; url: string; }) => {
let idCount = links.length;
const link = {
id: `link-${idCount++}`,
description: args.description,
url: args.url,
};
links.push(link);
return link;
},
},
};
export default resolvers;
const resolvers = {
// 省略
Mutation: {
post: (_parent: any, args: { description: string; url: string; }) => {
// 省略
},
},
};
yarn add -D @graphql-codegen/cli
yarn graphql-code-generator init
overwrite: true
schema: "src/schema.graphql"
generates:
src/types/graphql.d.ts:
config:
useIndexSignature: true
plugins:
- "typescript"
- "typescript-resolvers"
yarn graphql-codegen --config codegen.yml
import { Resolvers } from "./types/graphql";
// resolver
const resolvers: Resolvers = { // Resolversの型注釈を追加
// 省略
Mutation: {
post: (_parent, args) => { // 引数に型注釈が必要ない
let idCount = links.length;
const link = {
id: `link-${idCount++}`,
description: args.description,
url: args.url,
};
links.push(link);
return link;
},
},
};