UNPKG

2.75 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6const ansi_colors_1 = __importDefault(require("ansi-colors"));
7function generateUUID() {
8 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
9 const r = (Math.random() * 16) | 0, v = c === "x" ? r : (r & 0x3) | 0x8;
10 return v.toString(16);
11 });
12}
13exports.generateUUID = generateUUID;
14function primaryKeyTypeSafetyCheck(targetPrimaryKeyType, primaryKey, modelName) {
15 const primaryKeyType = typeof primaryKey;
16 if (targetPrimaryKeyType === "id" && primaryKeyType !== "number") {
17 throw new Error(ansi_colors_1.default.red(`[Memserver] ${modelName} model primaryKey type is 'id'. Instead you've tried to enter id: ${primaryKey} with ${primaryKeyType} type`));
18 }
19 else if (targetPrimaryKeyType === "uuid" && primaryKeyType !== "string") {
20 throw new Error(ansi_colors_1.default.red(`[Memserver] ${modelName} model primaryKey type is 'uuid'. Instead you've tried to enter uuid: ${primaryKey} with ${primaryKeyType} type`));
21 }
22 return targetPrimaryKeyType;
23}
24exports.primaryKeyTypeSafetyCheck = primaryKeyTypeSafetyCheck;
25function insertFixturesWithTypechecks(modelDefinition, fixtures) {
26 const modelPrimaryKey = fixtures.reduce((primaryKeys, fixture) => {
27 const modelName = modelDefinition.name;
28 const primaryKey = (fixture.uuid ? "uuid" : null) || (fixture.id ? "id" : null);
29 if (!primaryKey) {
30 throw new Error(ansi_colors_1.default.red(`[Memserver] DATABASE ERROR: At least one of your ${modelName} fixtures missing a primary key. Please make sure all your ${modelName} fixtures have either id or uuid primaryKey`));
31 }
32 else if (primaryKeys.includes(fixture[primaryKey])) {
33 throw new Error(ansi_colors_1.default.red(`[Memserver] DATABASE ERROR: Duplication in ${modelName} fixtures with ${primaryKey}: ${fixture[primaryKey]}`));
34 }
35 modelDefinition.insert(fixture);
36 return primaryKeys.concat([fixture[primaryKey]]);
37 }, [])[0];
38 return fixtures;
39}
40exports.insertFixturesWithTypechecks = insertFixturesWithTypechecks;
41function getModelPrimaryKey(model, existingPrimaryKeyType, modelName) {
42 if (existingPrimaryKeyType) {
43 return primaryKeyTypeSafetyCheck(existingPrimaryKeyType, model[existingPrimaryKeyType], modelName);
44 }
45 const primaryKey = model.id || model.uuid;
46 if (!primaryKey) {
47 return;
48 }
49 existingPrimaryKeyType = model.id ? "id" : "uuid";
50 return primaryKeyTypeSafetyCheck(existingPrimaryKeyType, primaryKey, modelName);
51}