How to make @fastify/mongodb plugin TS compatible with Mongo GridFS?

43 views Asked by At

Trying to create a Fastify based Node.js backend, that uses MongoDB as its database and the GridFS module. The problem is I can't make fastify/mongodb plugin work with Typescript even with interface merging.

What am I missing to have a new, self defined property in fastify.mongo object (named buckets in this scenario) with TS support?

It can be done if I create a new property on the Fastify instance itself (e.g. fastify.buckets), but it would be greater if all mongo related ones could be under fastify.mongo property.

I tried this, it reports some merging errors, but logs a correct GridFS object:

TS2717: Subsequent property declarations must have the same type. Property mongo must be of type FastifyMongoObject & FastifyMongoNestedObject, but here has type { buckets: Record<string, GridFSBucket>; }


import fastifyMongodb from "@fastify/mongodb";
import type {FastifyPluginAsync} from "fastify";

const mongodb: FastifyPluginAsync = async (fastify) => {
    await fastify.register(fastifyMongodb, {
        auth: {
            password: fastify.config.INITDB_ROOT_PASSWORD,
            username: fastify.config.INITDB_ROOT_USER,
        },
        url: `mongodb://${fastify.config.DB_HOST}:${fastify.config.DB_PORT}`,
        name: "default",
        database: "default",
        forceClose: true,
    });

    const templatesBucket = new fastifyMongodb.mongodb.GridFSBucket(fastify.mongo.db!, {
        bucketName: "templates",
    });

    const docsBucket = new fastifyMongodb.mongodb.GridFSBucket(fastify.mongo.db!, {
        bucketName: "docs",
    });


    fastify.mongo.buckets = {
        templates: templatesBucket,
        docs: docsBucket,
    }

};

declare module 'fastify' {
    interface FastifyInstance {
        mongo: {
            buckets: Record<string, fastifyMongodb.mongodb.GridFSBucket>;
        };
    }
}


export default mongodb;
0

There are 0 answers