@gent-js/gent
Version:
template-based data generator.
71 lines (70 loc) • 2.48 kB
JavaScript
import { faker } from "@faker-js/faker";
import { DateTime } from "luxon";
import { parseString } from "../../../utils.js";
const NO_DATE = "NO_DATE";
const ERROR_DATE = "ERROR_DATE";
/**
* options
* * format
*/
class TimestampCommandImpl {
name = "timestamp";
dateTimeArray;
sharedDocumentOptions;
build(commandOptions, documentOptions) {
// initialize date values
const sharedDocumentOptions = documentOptions.shared;
const mySharedDocumentOptions = this.sharedDocumentOptions;
if (mySharedDocumentOptions === undefined) {
this.sharedDocumentOptions = sharedDocumentOptions;
}
else if (mySharedDocumentOptions !== sharedDocumentOptions) {
console.error("call timestamp build with the different shared document options, which is unexpected.");
}
// process option
const format = parseString(commandOptions?.["format"]);
if (format !== undefined) {
return (context) => {
const dateTime = this.getDateTime(context);
if (dateTime === undefined) {
return NO_DATE;
}
else {
return dateTime.toFormat(format);
}
};
}
else {
return (context) => {
const dateTime = this.getDateTime(context);
if (dateTime === undefined) {
return NO_DATE;
}
else {
return dateTime.toISO() ?? ERROR_DATE;
}
};
}
}
getDateTime(context) {
let dateTimeArray = this.dateTimeArray;
if (dateTimeArray === undefined) {
const sharedDocumentOptions = this.sharedDocumentOptions;
if (sharedDocumentOptions === undefined) {
console.error("run timestamp command before build.");
return undefined;
}
const options = {
from: sharedDocumentOptions.from,
to: sharedDocumentOptions.to,
count: sharedDocumentOptions.total,
};
dateTimeArray = faker.date
.betweens(options)
.map((date) => DateTime.fromJSDate(date));
this.dateTimeArray = dateTimeArray;
}
return dateTimeArray[context.index];
}
}
export const timestampCommand = new TimestampCommandImpl();