我正在尝试使用faker包为Typescript中的模型建立工厂。我已经设法创建了一个功能齐全的通用工厂,例如休闲包api,该工厂可以接收通用模型制作者以及用于覆盖所创建模型的选项。该通用工厂生成模型工厂,因此其工厂生成工厂。这个生成的工厂可以接收两个参数,第一个是我要制作的模型数量,默认值为1,第二个参数是我要在模型上覆盖的选项。我遇到的问题是,我不知道是否有可能根据数量值自动确定工厂的退货类型,例如,如果数量为一,我应该退货,IModel
但是如果数量大于一我应该回来IModel[]
。
现在,我已经明确地返回IModel | IModel[]
return,并且每当我使用工厂时,都必须像下面这样键入return:
jest.spyOn(registerUserStub, 'execute').mockResolvedValueOnce(userFactory(1) as IUserModel)
我的代码:
// My User Model
export type IUserModel = {
id: string,
name: string,
email: string,
password: string,
active: boolean,
confirmed: boolean
}
工厂制造商
import { DeepPartial } from 'utility-types'
export function factoryMaker<T = any> (objMaker: (options?: DeepPartial<T>) => T): (quantity: number, options?: DeepPartial<T>) => T | T[] {
return (quantity, options) => {
const entitiesArray = new Array(quantity).fill(null).map(() => objMaker(options))
return quantity === 1 ? entitiesArray[0] : entitiesArray
}
}
我的用户工厂
import { DeepPartial } from 'utility-types'
import faker from 'faker'
import { IUserModel } from '../models'
import { factoryMaker } from './factoryMaker'
type OptionsType = DeepPartial<IUserModel>
function makeUser (options?: OptionsType):IUserModel {
return {
id: faker.random.uuid(),
password: faker.random.uuid(),
email: faker.internet.email(),
name: faker.name.findName(),
confirmed: options.confirmed !== undefined ? options.confirmed : true,
active: true,
...options
}
}
const userFactory = factoryMaker<IUserModel>(makeUser)
export { userFactory }
您可以factoryMaker
退货N extends 1 ? T : T[]
,N
数量在哪里:
export function factoryMaker<T = any>(
objMaker: (options?: DeepPartial<T>) => T
): <N extends number>(
quantity: N,
options?: DeepPartial<T>
) => N extends 1 ? T : T[] {
return <N extends number>(
quantity: N,
options?: DeepPartial<T>
): N extends 1 ? T : T[] => {
const entitiesArray = new Array(quantity).fill(null).map(() => objMaker(options))
return (quantity === 1 ? entitiesArray[0] : entitiesArray) as N extends 1 ? T : T[]
}
}
// ...
// IUserModel
const oneUser = userFactory(1)
// IUserModel[]
const twoUsers = userFactory(2)
// IUserModel | IUserModel[]
const oneOrTwoUsers = userFactory(Math.random() > 0.5 ? 1 : 2)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句