I'm learning to use Nuxt, and currently trying nuxt-bridge which comes with most of Nuxt3 functions, while keeping nuxt-auth-next module compatibily which I need.
As of now I'm working on my API, using Nuxt3 /server/api
and /server/middleware
directories. Everything runs on nuxi/nitro
.
This is a small example of API route (/server/api/me.get.ts
: gets user info from JWT token, code has been simplified here) :
// /server/api/me.get.ts
import mysql, { RowDataPacket } from 'mysql2/promise'
import { defineEventHandler, getRequestHeader } from 'h3' // Needed since nuxt-bridge wont auto import dependencies in /server/...
import { useRuntimeConfig } from '#imports' // fails but code still works... ESM absolute path needed
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
try {
const db = await mysql.createPool(config.mysql)
// ... Core route logic : getting user info from token and sending it back
} catch (e) {
// Managing error
}
})
This actually works as intended. My problem is that i'm using the same code for establishing MySQL connection in every route (login.post.ts
, register.post.ts
...) which is redundent and not quite elegant.
I would then like to use a serverMiddleware to establish the connection for every route.
So first of all, is this correct practice/use of serverMiddleware ?
Then, I have trouble finding how to properly achieve it. I created a /server/middleware/database.ts
which is fired every time an API call is made. But I have no clue how to establish mysql connection from it and passing it to the actual called route.
I tried fiddling with request/response as follow (seen in a tutorial) :
// /server/middleware/database.ts
import type { IncomingMessage, ServerResponse } from 'http'
import mysql from 'mysql2/promise'
import { defineHandler } from 'h3' // Needed since nuxt-bridge wont auto import dependencies
import { useRuntimeConfig } from '#imports' // fails but code still works... ESM absolute path needed
export default defineHandler(
async (req: IncomingMessage, res: ServerResponse) => {
const config = useRuntimeConfig()
try {
req['db'] = await mysql.createPool(config.mysql)
} catch (e) {
console.log('error')
}
}
)
And then using it like so :
// /server/api/test.get.ts
import type { IncomingMessage, ServerResponse } from 'http'
import { defineHandler } from 'h3' // Needed since nuxt-bridge wont auto import dependencies
import { useRuntimeConfig } from '#imports' // fails but code still works... ESM absolute path needed
export default defineHandler(
async (req: IncomingMessage, res: ServerResponse) => {
const [test] = req['db'].query('SELECT * FROM users')
// Core logic
}
)
But it does not work. I'm stuck :). Please note that it's been quite some time since I used Javascript and that it's my first steps en Typescript.
Any help would be greatly appreciated.
const db = "test"
(instead of//your code...
) then in /api/test.tsconsole.log(db)
the db variable is unknown. – Addis