Is there a more efficient way to make calls to different collections based on a function parameter? I'm exploring the possibility and if it's not feasible, I'll handle it case by case.
Currently, I have this code and the goal is to have a unified create
method for all three collections, as initially planned.
However, TypeScript throws an error stating "This expression is not callable.
Each member of the union type 'my 3 types' has signatures, but none of those signatures are compatible with each other." when calling insertOne
(the usage of this[collection]
is correct).
import { Collection, Db, InsertOneResult, ObjectId } from "mongodb";
export type L1CategoryDocument = L1Category & {
_id: ObjectId;
};
export type L2CategoryDocument = L2Category & {
_id: ObjectId;
};
export type L3CategoryDocument = L3Category & {
_id: ObjectId;
};
export class CategoryClient {
private l1: Collection<L1CategoryDocument>;
private l2: Collection<L2CategoryDocument>;
private l3: Collection<L3CategoryDocument>;
constructor(db: Db) {
this.l1 = db.collection("l1");
this.l2 = db.collection("l2");
this.l3 = db.collection("l3");
}
async create(collection: "l1", category: L1Category): Promise<InsertOneResult>;
async create(collection: "l2", category: L2Category): Promise<InsertOneResult>;
async create(collection: "l3", category: L3Category): Promise<InsertOneResult>;
async create(
collection: "l1" | "l2" | "l3",
category: L1Category | L2Category | L3Category,
): Promise<InsertOneResult> {
return this[collection].insertOne(category);
}
}