【发布时间】:2019-07-05 08:18:34
【问题描述】:
我正在尝试使用 facebook 数据加载器实现存储库通用模式。
此代码用于 GraphQL API。
抽象基类,我得到错误了吗:
import { Collection, Db, InsertOneWriteOpResult, ObjectId } from "mongodb";
import { RepositoryGeneric } from "../../types/database";
export default abstract class BaseRepository<TEntity, TLoaders> implements RepositoryGeneric<TEntity> {
protected mongoCollection: Collection<TEntity>;
protected dataLoaders: TLoaders;
public constructor(database: Db, collection: string, loaders: TLoaders) {
this.mongoCollection = database.collection(collection);
this.dataLoaders = loaders;
}
public async findOne(id: ObjectId | string): Promise<TEntity | null> {
if (typeof id === "string") {
id = ObjectId.createFromHexString(id);
}
// This line is producing the error
return this.dataLoaders.id.load(id);
}
public async create(entity: TEntity): Promise<TEntity> {
const result: InsertOneWriteOpResult = await this.mongoCollection.insertOne(entity);
if (!result.result.ok) {
throw new Error();
}
return result.ops[0];
}
}
类扩展抽象基类:
import { MongoClient } from "mongodb";
import { EntityBusiness } from "../../types/database";
import BusinessLoaders from "../loaders/businessLoaders";
import BaseRepository from "./baseRepository";
export default class BusinessRepository extends BaseRepository<EntityBusiness, BusinessLoaders> {
public constructor(mongoClient: MongoClient, businessLoaders: BusinessLoaders) {
super(mongoClient.db(), "business", businessLoaders);
// tslint:disable-next-line: no-console
console.log(businessLoaders.id);
}
}
实现数据加载器的类:
import DataLoader from "dataloader";
import { AggregationCursor, Collection, MongoClient, ObjectId } from "mongodb";
import { EntityBusiness, LoaderCommon } from "../../types/database";
export default class BusinessLoaders implements LoaderCommon<EntityBusiness> {
private idLoader: DataLoader<ObjectId, EntityBusiness>;
public constructor(mongoClient: MongoClient) {
this.idLoader = new DataLoader((keys) => this.idBatch(mongoClient, keys), {
cacheKeyFn: (key) => key.toHexString(),
});
}
public get id(): DataLoader<ObjectId, EntityBusiness> {
return this.idLoader;
}
private async idBatch(mongoClient: MongoClient, keys: ObjectId[]): Promise<EntityBusiness[]> {
const collection: Collection<EntityBusiness> = mongoClient.db().collection("business");
const aggregation: AggregationCursor<EntityBusiness> = collection.aggregate([
{ $match: { _id: { $in: keys } } },
{ $addFields: { __order: { $indexOfArray: [keys, "$_id"] } } },
{ $sort: { __order: 1 } },
{ $project: { __order: 0 } },
]);
return aggregation.toArray();
}
}
我对打字稿没有太多经验,但我希望不会出错。相反,我得到错误:
错误 TS2339:“TLoaders”类型上不存在属性“id”。
【问题讨论】:
标签: typescript