这两天学习了下 GraphQL,用 Koa2, GraphQL, MySQL, TypeORM,进行了一个实践。
感觉GraphQL挺好用的,可能会成为我之后经常使用的方法。
记录一下实践过程。
项目地址:https://github.com/TonyGoods/koa2_graphql_mysql_typeorm.git
引入Koa2
yarn add koa
在 src/server.js 文件中加入以下代码,
import Koa from "koa";
const app = new Koa();
app.use(async (ctx) => {
ctx.body = "hello world!";
});
app.listen(3000);
运行文件后,在浏览器中打开 http://localhost:3000 ,可以看到输出 hello world! 。
引入 TypeORM, MySQL
yarn add typeorm reflect-metadata mysql typescript
添加文件 tsconfig.json,实现对 typescript 的支持,
{
"compilerOptions": {
"target": "ES2017",
"module": "commonjs",
"lib": ["es6"],
"sourceMap": true,
"outDir": "dist",
"noImplicitAny": true,
"strictNullChecks": true,
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"*": ["node_modules/*"]
},
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
添加 ormconfig.js 文件,配置 TypeORM
module.exports = {
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: process.env.DB_PASSWORD,
database: "school",
synchronize: true,
entities: ["src/entity/*.ts"],
cli: {
entitiesDir: "src/entity",
},
};
在 src/entity/student.ts 中定义实体
import {
Entity, Column, PrimaryGeneratedColumn } from "typeorm"

本文介绍了如何使用Koa2、GraphQL、MySQL和TypeORM进行实践操作。通过项目实践,作者体验到GraphQL的便捷,并分享了从引入Koa2、配置TypeORM和MySQL,到实现GraphQL查询的完整过程。项目源码可在GitHub找到。

1002

被折叠的 条评论
为什么被折叠?



