Next.js配置使用typeorm实现自动entity同步

Next.js可以很方便的搞一些需要轻量后端的react网站。不过本身并没有提供MySQL的连接支持 ,习惯了使用typeorm后,对于直接写sql实在无法忍受,于是尝试在next.js中引入typeorm。

首先安装typeorm相关依赖

yarn add typeorm mysql reflect-metadata

创建一个测试entity: entities/user.entity.ts

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;
}

放置entity总入口:entities/index.ts

export * from './user';

创建初始化文件orm.ts

import "reflect-metadata";
import { Connection, getConnectionManager } from 'typeorm';
import { User } from './entities/index';

const options = {
  default: {
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'awesome',
      synchronize: true,
      entities: [
          User,
      ]
  },
};

function entitiesChanged(prevEntities: any[], newEntities: any[]): boolean {
  if (prevEntities.length !== newEntities.length) return true;

  for (let i = 0; i < prevEntities.length; i++) {
    if (prevEntities[i] !== newEntities[i]) return true;
  }

  return false;
}

async function updateConnectionEntities(connection: Connection, entities: any[]) {
  if (!entitiesChanged(connection.options.entities, entities)) return;

  // @ts-ignore
  connection.options.entities = entities;

  // @ts-ignore
  connection.buildMetadatas();

  if (connection.options.synchronize) {
    await connection.synchronize();
  }
}

export async function ensureConnection(name: string = 'default'): Promise<Connection> {
  const connectionManager = getConnectionManager();

  if (connectionManager.has(name)) {
    const connection = connectionManager.get(name);

    if (!connection.isConnected) {
      await connection.connect();
    }

    if (options[name].synchronize) {
      await updateConnectionEntities(connection, options[name].entities);
    }

    return connection;
  }

  return await connectionManager.create({ name, ...options[name] }).connect();
}

export async function getRepository<T>(entity: any) {
    const connection = await ensureConnection();
    return connection.manager.getRepository<T>(entity);
}

使用repository

import { User } from "./entities/user";
export default async (req, res) => {
    const userRepository = await getRepository<User>(User);
    const users = await userRepository.find();
    res.status(200).json(users);
}

next.js是serverless模式,不会在项目启动的时候执行我们的代码,也没有显式的初始化函数。因此自动同步将会发生在首个请求中。

文章原始链接:https://sijie.wang/posts/nextjs-typeorm

本站文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请保留原始链接