UNPKG

gen-jhipster

Version:

VHipster - Spring Boot + Angular/React/Vue in one handy generator

36 lines (35 loc) 1.98 kB
import { camelCase, upperFirst } from 'lodash-es'; import { upperFirstCamelCase } from "./string.js"; export const flatChoices = (choices) => choices.map(choice => (typeof choice === 'string' ? choice : choice.value)).filter(Boolean); export const derivedPropertyName = (property, value, suffix) => { const cleaned = value.replaceAll(/[^a-z0-9-]/gi, ''); const valueProperty = cleaned.includes('-') ? upperFirstCamelCase(cleaned) : upperFirst(cleaned); const camelCaseProperty = camelCase(property); return `${camelCaseProperty}${valueProperty}${suffix ?? ''}`; }; export const applyDerivedProperty = (data, property, possibleValues, { addAny, addNo, defaultValue = 'no' } = {}) => { const camelCaseProp = camelCase(property); let actualValue = data[camelCaseProp] ?? defaultValue; actualValue = actualValue === false && possibleValues.includes('no') ? 'no' : actualValue; const flattenedChoices = flatChoices(possibleValues); let isAny = false; for (const value of flattenedChoices) { const isProperty = Array.isArray(actualValue) ? actualValue.includes(value) : actualValue === value; data[derivedPropertyName(property, value)] ??= isProperty; if (isProperty && value !== 'no') { isAny = true; } } if (addAny) { data[derivedPropertyName(property, 'any')] ??= isAny; } if (addNo) { if (flattenedChoices.includes('no')) { throw new Error('Possible values already include "no"'); } data[derivedPropertyName(property, 'no')] ??= !isAny; } }; export const buildMutateDataForProperty = (property, possibleValues, { prefix = property, suffix = '', array, valCheck = array ? (data, value) => data[property]?.includes(value) ?? false : (data, value) => data[property] === value, } = {}) => { return Object.fromEntries(possibleValues.map(value => [derivedPropertyName(prefix, value, suffix), (data) => valCheck(data, value)])); };