Skip to content

Instantly share code, notes, and snippets.

@rodrigocnascimento
Last active March 2, 2023 01:14
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 rodrigocnascimento/c65980d7e6cc39fc1e05fceaf30d453c to your computer and use it in GitHub Desktop.
Save rodrigocnascimento/c65980d7e6cc39fc1e05fceaf30d453c to your computer and use it in GitHub Desktop.
export interface MockDataOptions {
customData?: Record<string, any>;
quantityToGenerate?: number;
}
function customObjectPropertyOverload(index: any, customData: any, mockedData: any) {
const dataPropertyKeys = Object.keys(customData || {});
for (const dataIndex of dataPropertyKeys) {
const dataSubProperties = Object.keys(customData[dataIndex]);
if (typeof customData[dataIndex] !== "object") {
mockedData[index][dataIndex] = customData[dataIndex];
} else {
for (const dataSubIndex of dataSubProperties) {
mockedData[index][dataIndex][dataSubIndex] = customData[dataIndex][dataSubIndex];
}
}
}
return mockedData;
}
export function createMockData(
entityObject: Record<string, any>,
customData: MockDataOptions["customData"] = {}
) {
let mockedData = [];
const quantityToGenerate = entityObject.length || 1;
for (const [index, entity] of Object.entries(entityObject)) {
mockedData.push(entity);
mockedData = customObjectPropertyOverload(index, customData, mockedData);
}
return quantityToGenerate > 1 ? mockedData : mockedData.shift();
}
// implementing
import { MockDataOptions, createMockData } from "./autoMock";
import { faker } from "@faker-js/faker";
import { UserRoles } from "../../users/user.entity";
function defaultData(customData = {} as any, quantityToGenerate = 1) {
return [...Array(quantityToGenerate).keys()].map(() => {
const {
id = faker.datatype.uuid(),
name = faker.name.fullName(),
email = faker.internet.email(),
role = faker.helpers.arrayElement([UserRoles.ADMIN, UserRoles.DOCTOR, UserRoles.PATIENT]),
password = faker.internet.password(),
createdAt = new Date(),
updatedAt = new Date(),
userAppointments = [],
} = customData;
return {
id,
name,
email,
role,
password,
createdAt,
updatedAt,
userAppointments,
};
});
}
export function build(options: MockDataOptions = {}) {
const { customData, quantityToGenerate } = options;
const entityObject = defaultData(customData, quantityToGenerate);
return createMockData(entityObject, customData);
}
// using to generate data
const [patient1, patient2] = patientMock({
quantityToGenerate: 2,
});
// overloading some properties
const secondMedicalApp = medicalAppointmentMock({
customData: {
doctor: doctor.id,
patient: patient2.id,
date: new Date(),
createdAt: new Date(),
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment