Last active
July 15, 2020 14:36
-
-
Save if1live/feb840d1499450fc3abe21ed1d56af6a to your computer and use it in GitHub Desktop.
generic based rosie constructor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Factory } from 'rosie'; | |
import { NonFunctionKeys } from 'utility-types'; | |
// maybe typeorm entity | |
class Entity { | |
constructor() { | |
this.a = 0; | |
this.b = null; | |
} | |
public a: number; | |
public b: Date | null; | |
public f() { return 1; } | |
} | |
function create_simple( | |
...params: Partial<Entity>[] | |
): Entity { | |
const { | |
a, | |
b, | |
} = params[0]; | |
const ent = new Entity(); | |
ent.a = a!; | |
ent.b = b!; | |
return ent; | |
} | |
function generate<T extends object>(ctor: new () => T) { | |
return (...params: Partial<T>[]) => { | |
const skel = params[0]; | |
const keys = Object.keys(skel) as NonFunctionKeys<T>[]; | |
const ent = new ctor(); | |
for (const key of keys) { | |
if (skel[key] !== undefined) { | |
ent[key] = skel[key]!; | |
} | |
} | |
return ent; | |
}; | |
} | |
Factory.define<Entity>('data_simple', create_simple) | |
.attr('a', () => 1) | |
.attr('b', () => null); | |
Factory.define<Entity>('data_generic', generate(Entity)) | |
.attr('a', () => 2) | |
.attr('b', () => null); | |
function main() { | |
const x = Factory.build<Entity>('data_simple', { a: 12, b: new Date() }); | |
console.log(x); | |
const y = Factory.build<Entity>('data_generic', { a: 123, b: new Date() }); | |
console.log(y); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment