Midway 使用 SQLite3

CREATE TABLE todo(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,title TEXT);
1
npm init midway

yarn add @midwayjs/orm typeorm sqlite3
1
2
3

配置

// configuration.ts
import { Configuration } from "@midwayjs/decorator";
import * as orm from "@midwayjs/orm";
import { join } from "path";

@Configuration({
  imports: [orm], //  加载 orm 组件
  importConfigs: [join(__dirname, "./config")],
})
export class ContainerConfiguratin {}






 



1
2
3
4
5
6
7
8
9
10

配置:

export const orm = {
  type: "sqlite",
  database: path.join(__dirname, "../../dev.sqlite"),
  synchronize: false, // 如果第一次使用,不存在表,有同步的需求可以写 true
  logging: true,
};
1
2
3
4
5
6

代码

entity

import { EntityModel } from "@midwayjs/orm";
import { Column, PrimaryGeneratedColumn } from "typeorm";

@EntityModel("todo")
export class Todo {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: "title" })
  text: string;
}
1
2
3
4
5
6
7
8
9
10
11

Controller

import { Inject, Controller, Provide, Get } from "@midwayjs/decorator";
import { Context } from "egg";
import { IGetUserResponse } from "../interface";
import { TodoService } from "../service/todo";

//
import { v4 as uuidv4 } from "uuid";
import { InjectEntityModel } from "@midwayjs/orm";
import { Repository } from "typeorm";
import { Todo } from "../entity/todo";

@Provide()
@Controller("/api")
export class APIController {
  @Inject()
  ctx: Context;

  @Inject()
  service: TodoService;

  @InjectEntityModel(Todo)
  todoModel: Repository<Todo>;

  @Get("/")
  async getTodo(): Promise<IGetUserResponse> {
    const list = await this.todoModel.find();
    return { success: true, message: "OK", data: list };
  }

  @Get("/add")
  async getUser(): Promise<IGetUserResponse> {
    const uuid: string = uuidv4();
    const user = await this.todoModel.save({ text: uuid });
    return { success: true, message: "OK", data: user };
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36