【发布时间】:2021-05-14 09:02:22
【问题描述】:
我的用户 ID CustomerID 和 ProviderID 有自定义标量,我想在有人调用突变时验证它们以确保给定 ID 与用户匹配并且类型正确。
我们无法使 CustomerScalar parseValue 方法异步,所以我正在寻找一种处理此类事情的好方法。
也许是 customerDecorator ?我不知道 ?任何想法 ? 我想使用依赖注入访问我的存储库,以确保传递的 ID 存在于数据库中并且确实是客户。 Field Middleware and Directive似乎不支持Deps注入。
@InputType()
export class CreateBillInput {
@Field(() => CustomerIDScalar)
customerID: CustomerID;
@Field()
name: string;
@Field(() => Int)
amount: number;
}
我想要的却行不通:
@Injectable()
export class CustomerIDScalar implements CustomScalar<string, CustomerID> {
constructor(private userRepository: IUserRepository) {}
parseValue(value: string) {
return this.getCustomerID(value);
}
parseLiteral(ast: ValueNode) {
if (ast.kind !== Kind.STRING) {
throw new TypeError('Argument is not a string value.');
}
return this.getCustomerID(value);;
}
serialize(value: CustomerID) {
return value.value; // value sent to the client
}
// TODO: Not usable here
private async getCustomerID(userID: string): Promise<CustomerID> {
const user = await this.userRepository.getByID(userID);
if (!user || !user.isCustomer()) {
throw new BadRequestException('There is no such customer user for provided ID.');
}
return user.id as CustomerID;
}
}
谢谢
【问题讨论】: