安裝
- 安裝主包
npm i graphql @types/graphql type-graphql
- 安裝reflect-metadata,用來做類型反射
npm i reflect-metadata
注意: 我們必須確保該包在我們使用/導入 type-graphql或者我們的resolvers之前引用reflect-metadata,如下
import "reflect-metadata";
TypeScript配置
- tsconfig.json配置如下選項
{
"emitDecoratorMetadata": true,
"experimentalDecorators": true
}
- 因為TypeGraphQL基于Node.js LTS (8, 10) ,它使用了ES7(ES2016)的語法,所以還必須設置
{
"target": "es2016" // or newer if your node.js version supports this
}
- 由于graphql的訂閱依賴AsyncIterator,所以我們還必須配置esnext.asynciterable
{
"lib": ["es2016", "esnext.asynciterable"]
}
所有,總結上面的,tsconfig.json需要添加如下選項:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"lib": ["es2016", "esnext.asynciterable"],
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
具體使用方法可以參考: Nest-Graphql的使用
,因為Nest也是基于TypeGraphql開發(fā)的,所以基本都差不多。下面介紹些額外的知識。
部署Graphql Server
因為typegraphql沒有單獨的部署server的方法,所以我們這里會用到apollo-server-koa(node的框架是koa)
import { ApolloServer } from 'apollo-server-koa';
然后創(chuàng)建schema,遍歷加載所有的resolver
// 創(chuàng)建graphql的schema
const schema = await buildSchema({
resolvers: loadResolvers(path.join(__dirname, 'resolver')),
// automatically create `schema.gql` file with schema definition in project's working directory
emitSchemaFile: true,
});
// 加載所有resolver
function loadResolvers(dirPath: string): any[] {
// tslint:disable-next-line:prefer-const
let resolverArr: any[] = [];
if (!fs.existsSync(dirPath)) { return resolverArr; }
const list = fs.readdirSync(dirPath);
list.forEach((filename) => {
const file = path.join(dirPath, filename);
const module = require(file);
Object.keys(module).forEach((key) => {
resolverArr.push(module[key]);
});
});
return resolverArr;
}
最后就是創(chuàng)建server,并且應用于koa的中間件了
const server = new ApolloServer({
schema,
tracing: false,
playground: {
settings: {
'request.credentials': 'include',
},
} as any,
introspection: true,
});
const app = new Koa();
server.applyMiddleware({ app });
下來就可以通過 監(jiān)聽端口/graphql 訪問啦。