Next.js Discord

Discord Forum

How to provide api service after db initialize?

Unanswered
Little fire ant posted this in #help-forum
Open in Discord
Little fire antOP
I initialize my typeorm datasource:
export const AppDataSource = new DataSource({
  ...config
})

AppDataSource.initialize()
  .then(() => {
    console.log('db initialize done')
  })
  .catch((e) => console.log('init error', e))


and use the datasource in api route:
import { AppDataSource } from '@/db'
import { E2EProjectList } from '@/db/entity'

import { NextResponse } from 'next/server'
import chalk from 'chalk'

export async function GET(request: Request) {
  const res = await AppDataSource.manager.find(E2EProjectList)
  return NextResponse.json({ code: 200, data: res }, { status: 200 })
}

but in dev mode, the api route seems compile on demand? When i request the api, console output compiling the api, and throw an error, and then the api is ready, the after requests can be responsed as expect. how to let the api service avaliable after the db initialize ? Is there a lifecycle hook like beforeMount to do these initialize stuff?

0 Replies