//util file
async function dbconnector(fastify, options) {
try {
await client.connect()
console.log('db connected succesfully')
fastify.decorate('db', { client })
} catch(err) {
console.error(err)
}
}
module.exports = fastifyPlugin(dbconnector)
//index file
const dbconnector = require('./utils/db')
fastify.register(dbconnector)
whenever I try to do fastify.db it shows the below error
Property 'db' does not exist on type 'FastifyInstance<Server, IncomingMessage, ServerResponse, FastifyLoggerInstance> & PromiseLike
With the way Fastify have set up it's types you need to add the decorators yourself to the FastifyInstance. You can do that like so:
import { FastifyLoggerInstance, FastifyPluginAsync, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerBase, RawServerDefault } from 'fastify'
declare module 'fastify' {
export interface FastifyInstance<
RawServer extends RawServerBase = RawServerDefault,
RawRequest extends RawRequestDefaultExpression<RawServer> = RawRequestDefaultExpression<RawServer>,
RawReply extends RawReplyDefaultExpression<RawServer> = RawReplyDefaultExpression<RawServer>,
Logger = FastifyLoggerInstance
> {
db: FastifyPluginAsync;
}
}
You need to tell typescript to pick up this type file if you haven't already set it up in your tsconfig.json. An example of doing that would be this:
{
"compilerOptions": {
// ... your other config
"typeRoots": [
"types"
]
},
// ... the rest of your config
}
Then save the configuration in the root of your project under types/index.d.ts.
This tells the typescript compiler that you have defined your own types in that file. Extending the FastifyInstance to include your decorator should now work.