0

我正在尝试为 rxdb 创建一个插件。我想捕获由引发的异常insert并返回一个哈希 {[fieldName: string] => [error:string]}

但是,当使用我的新方法时,我遇到了一个异常,似乎该方法是直接在原型上而不是在每个RxColletion<T, T2, T3>实例上调用的。

我得到的错误是:

TypeError: Cannot read property 'fillObjectWithDefaults' of undefined

这发生在这里:https ://github.com/pubkey/rxdb/blob/ac9fc95b0eda276110f371afca985f949275c3f1/src/rx-collection.ts#L443

因为this.schema未定义..我在其上运行此方法的集合确实有一个模式..

这是我的插件代码:

export const validatedInsertPlugin: RxPlugin = {
    rxdb: true,
    prototypes: {
        RxCollection(proto: IRxCollectionBaseWithValidatedInsert) {
            proto.validatedInsert = async function validatedInsert<T, D>(
                doc: T
            ): Promise<Insert<T>> {
                try {
                    // this is the line that raises:
                    const product = await proto.insert(doc);
                    return [true, product];
                } catch (e) {
                    // extract errors
                    return [false, {} as Errors<T>];
                }
            };
        },
    },
    overwritable: {},
    hooks: {},
};
4

1 回答 1

1

为了回答我自己的问题,

proto.insert目标是原型,这不是我想要的。 function(this: RxCollection)是我想要的。我必须使用thiswhich 将针对实际实例。

proto.validatedInsert = async function validatedInsert<T1>(
                this: RxCollection,
                doc: T1
            ): Promise<ValidatedInsert<T1>> {
                try {
                    const product = await this.insert(doc); // this, not proto
                    return [true, product];
                } catch (e) {
    ...

于 2019-10-02T00:57:20.843 回答