Koa2, GraphQL, MySQL, TypeORM实践

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

这两天学习了下 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"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值