在 Nuxt 3 中使用 TypeORM

问题描述 投票:0回答:1

我正在尝试在 Nuxt 3 应用程序中使用 TypeORM。

我添加了 TypeORM 作为插件:

// plugins/typeorm.ts
import 'reflect-metadata';
import { defineNuxtPlugin } from '#app';
import { DataSource } from 'typeorm';
import { Events } from './../server/models/Events';

export default defineNuxtPlugin(async (nuxtApp) => {
  const AppDataSource = new DataSource({
    type: 'sqlite',
    database: 'database.sqlite',
    synchronize: true,
    logging: true,
    entities: [Events],
    migrations: [],
    subscribers: [],
  });

  if (!AppDataSource.isInitialized) {
    await AppDataSource.initialize();
  }

  nuxtApp.provide('db', AppDataSource);
});

更新了Nuxt配置文件:

// nuxt.config.ts
import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify';

export default defineNuxtConfig({
  devtools: { enabled: true },
  build: {
    transpile: ['vuetify'],
  },
  modules: [
    (_options, nuxt) => {
      nuxt.hooks.hook('vite:extendConfig', (config) => {
        config.plugins.push(vuetify({ autoImport: true }));
      });
    },
    '@nuxt/eslint',
    '@nuxt/test-utils/module',
  ],
  plugins: ['~/plugins/typeorm'],
  vite: {
    vue: {
      template: {
        transformAssetUrls,
      },
    },
  },
  typescript: {
    // strict: true,
    tsConfig: {
      compilerOptions: {
        target: 'es2020',
        module: 'ESNext',
        lib: ['dom', 'es2020'],
        moduleResolution: 'node',
        experimentalDecorators: true,
        emitDecoratorMetadata: true,
        strict: true,
        esModuleInterop: true,
        skipLibCheck: true,
        forceConsistentCasingInFileNames: true,
        baseUrl: '.',
      },
    },
  },
  nitro: {
    esbuild: {
      options: {
        tsconfigRaw: {
          compilerOptions: {
            experimentalDecorators: true,
          },
        },
      },
    },
  },

  compatibilityDate: '2024-07-25',
});

添加了 TypeORM 实体:

// server/models/Events.ts
import 'reflect-metadata';
import { Column, CreateDateColumn, Entity, PrimaryColumn, UpdateDateColumn } from 'typeorm';

@Entity()
export class Events {
  @PrimaryColumn({ type: 'varchar', unique: true, nullable: false })
  id!: string;

  @Column({ type: 'text', nullable: false })
  name!: string;

  @Column({
    type: 'datetime',
  })
  start_date_time!: string;

  @Column({ type: 'text', nullable: false })
  location!: string;

  @Column({ type: 'int', nullable: false })
  distance!: number;

  @Column({ type: 'float', nullable: true })
  elevation!: number;

  @Column({ type: 'text', nullable: false })
  website!: string;

  @Column({ type: 'text', nullable: true })
  logo!: string;

  @Column({ type: 'text', nullable: true })
  background_color!: string;

  @CreateDateColumn()
  created_at!: Date;

  @UpdateDateColumn()
  updated_at!: Date;
}

并从 api 调用它:

// server/api/events.ts
import { Events } from '../models/Events';
import { defineEventHandler, readBody } from 'h3';
import type { DataSource } from 'typeorm';

export default defineEventHandler(async (event) => {
  const appDataSource = event.context.nuxtApp.$db as DataSource;
  const eventsRepository = appDataSource.getRepository(Events);

  if (event.node.req.method === 'GET') {
    const events = await eventsRepository.find();
    return events;
  } else if (event.node.req.method === 'POST') {
    const body = await readBody(event);
    const events = eventsRepository.create(body);
    await eventsRepository.save(events);
    return events;
  }
});

当我启动服务器时,它启动正确,没有错误或警告日志:

$ yarn dev
yarn run v1.22.22
$ nuxt dev
Nuxt 3.12.3 with Nitro 2.9.7                                                                                                    18:14:08
                                                                                                                                18:14:08
  ➜ Local:    http://localhost:3000/
  ➜ Network:  use --host to expose

  ➜ DevTools: press Shift + Alt + D in the browser (v1.3.9)                                                                     18:14:09

ℹ Vite server warmed up in 2579ms                                                                                              18:14:13
ℹ Vite client warmed up in 2885ms                                                                                              18:14:13
✔ Nuxt Nitro server built in 708 ms                                                                                      nitro 18:14:13

但是在浏览器上,我收到以下错误:

Browser view showing 500 [vite-node] [PARSE_ERROR] /server/models/Events.ts at /server/models/Events.ts

浏览器控制台也没有真正帮助:

Browser console view of error: GET http://localhost:3000/ [HTTP/1.1 500 Vite Error 1035ms]

有人遇到过这个错误之王吗?有人在 Nuxt 3 中成功使用 TypeORM 了吗?

感谢您的帮助

vite typeorm nuxt3.js nitro
1个回答
0
投票

据我所知,

import 'reflect-metadata';
只需在应用程序启动时写入一次。

参见 github 的示例

https://github.com/will2hew/nuxt-typeorm/tree/main/src/runtime

© www.soinside.com 2019 - 2024. All rights reserved.