#How to access a database from server routes

5 messages · Page 1 of 1 (latest)

tiny mortar
#

Hello, i'm new to Nuxt (and vue). I have an app with sequelize installed and launched as a plugin :

export default defineNuxtPlugin(async () => {
    const config = useRuntimeConfig();

    const sequelize = new Sequelize({
        dialect: config.database.dialect as Dialect,
        storage: config.database.storage,
    });

    // ...

    return {
        provide: {
            db: sequelize,
        },
    };
});

I starts and creates my models as expected.
I'm using authjs (sidebase) for authentication, and I saw that there is a sequelize adapter (https://authjs.dev/reference/adapter/sequelize).

The problem is that when I try to call my plugin (const {$db} = useNuxtApp();), I get a Vue app aliases are not allowed in server routes.. I read (https://www.reddit.com/r/Nuxt/comments/15cli0t/using_nuxt_3_plugin_on_a_server_api_route/) that I may have to use a server middleware and add sequelize in the context.

My question is, how can I do that, should I export sequelize instance from the plugin or create a new one ?
Since I use a sqlite database (at least for the dev), won't there be any problem since sqlite is mono-user (it will have an instance in the plugin and the middleware) ?

Thanks for the help.

Reddit

Explore this post and more from the Nuxt community

exotic pilot
#

/server/utils/db.ts

export function useDb() {
  const config = useRuntimeConfig()

  const sequelize = new Sequelize({
    dialect: config.database.dialect as Dialect,
    storage: config.database.storage,
  })

  return sequelize
}
#

/server/api/hello.ts

#
export default defineEventHandler(async () => {
  try {
    // never used sequelize so I made up the query() method but you get the idea...
    const query = await useDb().query()

    return query
  }
  catch (error: any) {
    throw createError({
      statusCode: 500,
      statusMessage: error.message,
    })
  }
})