Skip to content

Instantly share code, notes, and snippets.

@if1live
Last active July 15, 2020 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save if1live/feb840d1499450fc3abe21ed1d56af6a to your computer and use it in GitHub Desktop.
Save if1live/feb840d1499450fc3abe21ed1d56af6a to your computer and use it in GitHub Desktop.
generic based rosie constructor
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