functional-models 1.0.28 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.eslintignore +1 -0
  2. package/.eslintrc +9 -15
  3. package/cucumber.js +10 -0
  4. package/features/arrayFields.feature +7 -7
  5. package/features/basic-ts.feature +13 -0
  6. package/features/functions.feature +2 -3
  7. package/package.json +33 -10
  8. package/src/constants.ts +15 -0
  9. package/src/{errors.js → errors.ts} +6 -4
  10. package/src/index.ts +11 -0
  11. package/src/interfaces.ts +323 -0
  12. package/src/{lazy.js → lazy.ts} +7 -9
  13. package/src/methods.ts +30 -0
  14. package/src/models.ts +183 -0
  15. package/src/properties.ts +375 -0
  16. package/src/serialization.ts +39 -0
  17. package/src/{utils.js → utils.ts} +16 -26
  18. package/src/validation.ts +390 -0
  19. package/{features/stepDefinitions/steps.js → stepDefinitions/oldSteps.ts} +76 -53
  20. package/stepDefinitions/tssteps.ts +107 -0
  21. package/test/src/errors.test.ts +31 -0
  22. package/test/src/{lazy.test.js → lazy.test.ts} +4 -4
  23. package/test/src/methods.test.ts +45 -0
  24. package/test/src/models.test.ts +417 -0
  25. package/test/src/{properties.test.js → properties.test.ts} +251 -58
  26. package/test/src/serialization.test.ts +80 -0
  27. package/test/src/{utils.test.js → utils.test.ts} +29 -7
  28. package/test/src/{validation.test.js → validation.test.ts} +278 -210
  29. package/tsconfig.json +100 -0
  30. package/src/constants.js +0 -19
  31. package/src/functions.js +0 -7
  32. package/src/index.js +0 -10
  33. package/src/models.js +0 -152
  34. package/src/properties.js +0 -313
  35. package/src/serialization.js +0 -50
  36. package/src/validation.js +0 -285
  37. package/test/base/index.test.js +0 -5
  38. package/test/src/functions.test.js +0 -45
  39. package/test/src/index.test.js +0 -5
  40. package/test/src/models.test.js +0 -380
  41. package/test/src/serialization.test.js +0 -127
package/tsconfig.json ADDED
@@ -0,0 +1,100 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Enable incremental compilation */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ "lib": ["es2021", "dom"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
22
+ // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+
26
+ /* Modules */
27
+ "module": "commonjs", /* Specify what module code is generated. */
28
+ //"rootDir": "./src" /* Specify the root folder within your source files. */,
29
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
30
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
31
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
32
+ "rootDirs": ["./src", "./stepDefinitions"], /* Allow multiple folders to be treated as one when resolving modules. */
33
+ // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
34
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
35
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
36
+ // "resolveJsonModule": true, /* Enable importing .json files */
37
+ // "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
38
+
39
+ /* JavaScript Support */
40
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
41
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
42
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
43
+
44
+ /* Emit */
45
+ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
46
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
47
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
48
+ "sourceMap": true, /* Create source map files for emitted JavaScript files. */
49
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
50
+ "outDir": "./dist" /* Specify an output folder for all emitted files. */,
51
+ // "removeComments": true, /* Disable emitting comments. */
52
+ // "noEmit": true, /* Disable emitting files from a compilation. */
53
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
54
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
55
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
56
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
57
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
58
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
59
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
60
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
61
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
62
+ // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
63
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
64
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
65
+ // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
66
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
67
+
68
+ /* Interop Constraints */
69
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
70
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
71
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
72
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
73
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
74
+
75
+ /* Type Checking */
76
+ "strict": true, /* Enable all strict type-checking options. */
77
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
78
+ // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
79
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
80
+ // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
81
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
82
+ // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
83
+ // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
84
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
85
+ // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
86
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
87
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
88
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
89
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
90
+ // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
91
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
92
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
93
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
94
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
95
+
96
+ /* Completeness */
97
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
98
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
99
+ }
100
+ }
package/src/constants.js DELETED
@@ -1,19 +0,0 @@
1
- const { getObjToArray } = require('./utils')
2
-
3
- const PROPERTY_TYPES = getObjToArray([
4
- 'UniqueId',
5
- 'DateProperty',
6
- 'ArrayProperty',
7
- 'ReferenceProperty',
8
- 'IntegerProperty',
9
- 'TextProperty',
10
- 'ConstantValueProperty',
11
- 'NumberProperty',
12
- 'ObjectProperty',
13
- 'EmailProperty',
14
- 'BooleanProperty',
15
- ])
16
-
17
- module.exports = {
18
- PROPERTY_TYPES,
19
- }
package/src/functions.js DELETED
@@ -1,7 +0,0 @@
1
- const Function = method => wrapped => () => {
2
- return method(wrapped)
3
- }
4
-
5
- module.exports = {
6
- Function,
7
- }
package/src/index.js DELETED
@@ -1,10 +0,0 @@
1
- module.exports = {
2
- constants: require('./constants'),
3
- ...require('./properties'),
4
- ...require('./models'),
5
- ...require('./functions'),
6
- errors: require('./errors'),
7
- validation: require('./validation'),
8
- serialization: require('./serialization'),
9
- utils: require('./utils'),
10
- }
package/src/models.js DELETED
@@ -1,152 +0,0 @@
1
- const merge = require('lodash/merge')
2
- const get = require('lodash/get')
3
- const { toObj } = require('./serialization')
4
- const { createModelValidator } = require('./validation')
5
- const { UniqueId, createPropertyTitle } = require('./properties')
6
-
7
- const MODEL_DEF_KEYS = ['meta', 'functions']
8
-
9
- const Model = (
10
- modelName,
11
- keyToProperty,
12
- {
13
- primaryKey = 'id',
14
- getPrimaryKeyProperty = () => UniqueId({ required: true }),
15
- instanceCreatedCallback = null,
16
- modelFunctions = {},
17
- instanceFunctions = {},
18
- modelValidators = [],
19
- } = {}
20
- ) => {
21
- /*
22
- * This non-functional approach is specifically used to
23
- * allow instances to be able to refer back to its parent without
24
- * having to duplicate it for every instance.
25
- * This is set at the very end and returned, so it can be referenced
26
- * throughout instance methods.
27
- */
28
- // eslint-disable-next-line functional/no-let
29
- let model = null
30
- keyToProperty = {
31
- // this key exists over keyToProperty, so it can be overrided if desired.
32
- [primaryKey]: getPrimaryKeyProperty(),
33
- ...keyToProperty,
34
- }
35
- const instanceProperties = Object.entries(keyToProperty).filter(
36
- ([key, _]) => MODEL_DEF_KEYS.includes(key) === false
37
- )
38
- const specialProperties1 = Object.entries(keyToProperty).filter(([key, _]) =>
39
- MODEL_DEF_KEYS.includes(key)
40
- )
41
- const properties = instanceProperties.reduce((acc, [key, property]) => {
42
- return merge(acc, { [key]: property })
43
- }, {})
44
- const specialProperties = specialProperties1.reduce(
45
- (acc, [key, property]) => {
46
- return merge(acc, { [key]: property })
47
- },
48
- {}
49
- )
50
-
51
- const create = (instanceValues = {}) => {
52
- // eslint-disable-next-line functional/no-let
53
- let instance = null
54
- const specialInstanceProperties1 = MODEL_DEF_KEYS.reduce((acc, key) => {
55
- if (key in instanceValues) {
56
- return { ...acc, [key]: instanceValues[key] }
57
- }
58
- return acc
59
- }, {})
60
- const loadedInternals = instanceProperties.reduce(
61
- (acc, [key, property]) => {
62
- const propertyGetter = property.createGetter(instanceValues[key])
63
- const propertyValidator = property.getValidator(propertyGetter)
64
- const getPropertyKey = createPropertyTitle(key)
65
- const fleshedOutInstanceProperties = {
66
- [getPropertyKey]: propertyGetter,
67
- functions: {
68
- getters: {
69
- [key]: propertyGetter,
70
- },
71
- validators: {
72
- [key]: propertyValidator,
73
- },
74
- },
75
- }
76
- const referenceProperties = get(property, 'meta.getReferencedId')
77
- ? {
78
- meta: {
79
- references: {
80
- [createPropertyTitle(`${key}Id`)]: () => property.meta.getReferencedId(instanceValues[key])
81
- }
82
- }
83
- }
84
- : {}
85
- return merge(acc, fleshedOutInstanceProperties, referenceProperties)
86
- },
87
- {}
88
- )
89
- const frameworkProperties = {
90
- meta: {
91
- getModel: () => model,
92
- },
93
- functions: {
94
- toObj: toObj(loadedInternals),
95
- getPrimaryKey: loadedInternals[createPropertyTitle(primaryKey)],
96
- validate: (options={}) => {
97
- return createModelValidator(
98
- loadedInternals,
99
- modelValidators
100
- )(instance, options)
101
- },
102
- },
103
- }
104
- const fleshedOutInstanceFunctions = Object.entries(
105
- instanceFunctions
106
- ).reduce((acc, [key, func]) => {
107
- return merge(acc, {
108
- functions: {
109
- [key]: (...args) => {
110
- return func(...args, instance)
111
- },
112
- },
113
- })
114
- }, {})
115
- instance = merge(
116
- {},
117
- loadedInternals,
118
- specialProperties,
119
- fleshedOutInstanceFunctions,
120
- frameworkProperties,
121
- specialInstanceProperties1
122
- )
123
- if (instanceCreatedCallback) {
124
- instanceCreatedCallback(instance)
125
- }
126
- return instance
127
- }
128
-
129
- const fleshedOutModelFunctions = Object.entries(modelFunctions).reduce(
130
- (acc, [key, func]) => {
131
- return merge(acc, {
132
- [key]: (...args) => {
133
- return func(model)(...args)
134
- },
135
- })
136
- },
137
- {}
138
- )
139
-
140
- // This sets the model that is used by the instances later.
141
- model = merge({}, fleshedOutModelFunctions, {
142
- create,
143
- getName: () => modelName,
144
- getProperties: () => properties,
145
- getPrimaryKeyName: () => primaryKey,
146
- })
147
- return model
148
- }
149
-
150
- module.exports = {
151
- Model,
152
- }
package/src/properties.js DELETED
@@ -1,313 +0,0 @@
1
- const identity = require('lodash/identity')
2
- const get = require('lodash/get')
3
- const isFunction = require('lodash/isFunction')
4
- const merge = require('lodash/merge')
5
- const {
6
- createPropertyValidator,
7
- emptyValidator,
8
- maxTextLength,
9
- minTextLength,
10
- minNumber,
11
- maxNumber,
12
- isType,
13
- referenceTypeMatch,
14
- meetsRegex,
15
- } = require('./validation')
16
- const { PROPERTY_TYPES } = require('./constants')
17
- const { lazyValue } = require('./lazy')
18
- const { toTitleCase, createUuid } = require('./utils')
19
-
20
- const createPropertyTitle = key => {
21
- const goodName = toTitleCase(key)
22
- return `get${goodName}`
23
- }
24
-
25
- const EMAIL_REGEX =
26
- /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/u
27
-
28
- const _getValidatorFromConfigElseEmpty = (config, key, validatorGetter) => {
29
- if (key in config) {
30
- return validatorGetter(config[key])
31
- }
32
- return emptyValidator
33
- }
34
-
35
- const _mergeValidators = (config, validators) => {
36
- return [...validators, ...(config.validators ? config.validators : [])]
37
- }
38
-
39
- const Property = (type, config = {}, additionalMetadata = {}) => {
40
- if (!type && !config.type) {
41
- throw new Error(`Property type must be provided.`)
42
- }
43
- if (config.type) {
44
- type = config.type
45
- }
46
- const getConstantValue = () => config.value !== undefined ? config.value : undefined
47
- const getDefaultValue = () => config.defaultValue !== undefined ? config.defaultValue : undefined
48
- const getChoices = () => config.choices ? config.choices : []
49
- const lazyLoadMethod = config.lazyLoadMethod || false
50
- const valueSelector = config.valueSelector || identity
51
- if (typeof valueSelector !== 'function') {
52
- throw new Error(`valueSelector must be a function`)
53
- }
54
-
55
-
56
- return {
57
- ...additionalMetadata,
58
- getConfig: () => config,
59
- getChoices,
60
- getDefaultValue,
61
- getConstantValue,
62
- getPropertyType: () => type,
63
- createGetter: instanceValue => {
64
- const value = getConstantValue()
65
- if (value !== undefined) {
66
- return () => value
67
- }
68
- const defaultValue = getDefaultValue()
69
- if (
70
- defaultValue !== undefined &&
71
- (instanceValue === null || instanceValue === undefined)
72
- ) {
73
- return () => defaultValue
74
- }
75
- const method = lazyLoadMethod
76
- ? lazyValue(lazyLoadMethod)
77
- : typeof instanceValue === 'function'
78
- ? instanceValue
79
- : () => instanceValue
80
- return async () => {
81
- return valueSelector(await method(instanceValue))
82
- }
83
- },
84
- getValidator: valueGetter => {
85
- const validator = createPropertyValidator(config)
86
- const _propertyValidatorWrapper = async (instance, instanceData, options={}) => {
87
- return validator(await valueGetter(), instance, instanceData, options)
88
- }
89
- return _propertyValidatorWrapper
90
- },
91
- }
92
- }
93
-
94
- const DateProperty = (config = {}, additionalMetadata={}) => Property(PROPERTY_TYPES.DateProperty, {
95
- ...config,
96
- lazyLoadMethod: value => {
97
- if (!value && config.autoNow) {
98
- return new Date()
99
- }
100
- return value
101
- },
102
- }, additionalMetadata)
103
-
104
- const ReferenceProperty = (model, config = {}, additionalMetadata={}) => {
105
- if (!model) {
106
- throw new Error('Must include the referenced model')
107
- }
108
-
109
- const _getModel = () => {
110
- if (isFunction(model)) {
111
- return model()
112
- }
113
- return model
114
- }
115
-
116
- const validators = _mergeValidators(config, [referenceTypeMatch(model)])
117
-
118
- const _getId = (instanceValues) => () => {
119
- if (!instanceValues) {
120
- return null
121
- }
122
- const theModel = _getModel()
123
- const primaryKey = theModel.getPrimaryKeyName()
124
- if (instanceValues[primaryKey]) {
125
- return instanceValues[primaryKey]
126
- }
127
- const primaryKeyFunc = get(instanceValues, 'functions.getPrimaryKey')
128
- if (primaryKeyFunc) {
129
- return primaryKeyFunc()
130
- }
131
- return instanceValues
132
- }
133
-
134
- const lazyLoadMethod = async instanceValues => {
135
-
136
- const valueIsModelInstance =
137
- Boolean(instanceValues) && Boolean(instanceValues.functions)
138
-
139
- const _getInstanceReturn = objToUse => {
140
- // We need to determine if the object we just go is an actual model instance to determine if we need to make one.
141
- const objIsModelInstance =
142
- Boolean(objToUse) && Boolean(objToUse.functions)
143
- const instance = objIsModelInstance
144
- ? objToUse
145
- : _getModel().create(objToUse)
146
- return merge({}, instance, {
147
- functions: {
148
- toObj: _getId(instanceValues),
149
- },
150
- })
151
- }
152
-
153
- if (valueIsModelInstance) {
154
- return _getInstanceReturn(instanceValues)
155
- }
156
- if (config.fetcher) {
157
- const id = await _getId(instanceValues)()
158
- const model = _getModel()
159
- const obj = await config.fetcher(model, id)
160
- return _getInstanceReturn(obj)
161
- }
162
- return _getId(instanceValues)()
163
- }
164
-
165
- return Property(
166
- PROPERTY_TYPES.ReferenceProperty,
167
- merge({}, config, {
168
- validators,
169
- lazyLoadMethod,
170
- }),
171
- {
172
- ...additionalMetadata,
173
- meta: {
174
- getReferencedId: (instanceValues) => _getId(instanceValues)(),
175
- getReferencedModel: _getModel,
176
- },
177
- }
178
- )
179
- }
180
-
181
- const ArrayProperty = (config = {}, additionalMetadata={}) =>
182
- Property(
183
- PROPERTY_TYPES.ArrayProperty,
184
- {
185
- defaultValue: [],
186
- ...config,
187
- isArray: true,
188
- }, additionalMetadata)
189
-
190
- const ObjectProperty = (config = {}, additionalMetadata={}) =>
191
- Property(
192
- PROPERTY_TYPES.ObjectProperty,
193
- merge(config, {
194
- validators: _mergeValidators(config, [isType('object')]),
195
- }),
196
- additionalMetadata
197
- )
198
-
199
- const TextProperty = (config = {}, additionalMetadata={} ) =>
200
- Property(
201
- PROPERTY_TYPES.TextProperty,
202
- merge(config, {
203
- isString: true,
204
- validators: _mergeValidators(config, [
205
- _getValidatorFromConfigElseEmpty(config, 'maxLength', value =>
206
- maxTextLength(value)
207
- ),
208
- _getValidatorFromConfigElseEmpty(config, 'minLength', value =>
209
- minTextLength(value)
210
- ),
211
- ]),
212
- }),
213
- additionalMetadata
214
- )
215
-
216
- const IntegerProperty = (config = {}, additionalMetadata={}) =>
217
- Property(
218
- PROPERTY_TYPES.IntegerProperty,
219
- merge(config, {
220
- isInteger: true,
221
- validators: _mergeValidators(config, [
222
- _getValidatorFromConfigElseEmpty(config, 'minValue', value =>
223
- minNumber(value)
224
- ),
225
- _getValidatorFromConfigElseEmpty(config, 'maxValue', value =>
226
- maxNumber(value)
227
- ),
228
- ]),
229
- }),
230
- additionalMetadata
231
- )
232
-
233
- const NumberProperty = (config = {}, additionalMetadata={}) =>
234
- Property(
235
- PROPERTY_TYPES.NumberProperty,
236
- merge(config, {
237
- isNumber: true,
238
- validators: _mergeValidators(config, [
239
- _getValidatorFromConfigElseEmpty(config, 'minValue', value =>
240
- minNumber(value)
241
- ),
242
- _getValidatorFromConfigElseEmpty(config, 'maxValue', value =>
243
- maxNumber(value)
244
- ),
245
- ]),
246
- }),
247
- additionalMetadata
248
- )
249
-
250
- const ConstantValueProperty = (value, config = {}, additionalMetadata={}) =>
251
- TextProperty(
252
- merge(config, {
253
- type: PROPERTY_TYPES.ConstantValueProperty,
254
- value,
255
- }),
256
- additionalMetadata
257
- )
258
-
259
- const EmailProperty = (config = {}, additionalMetadata={}) =>
260
- TextProperty(
261
- merge(config, {
262
- type: PROPERTY_TYPES.EmailProperty,
263
- validators: _mergeValidators(config, [meetsRegex(EMAIL_REGEX)]),
264
- }),
265
- additionalMetadata
266
- )
267
-
268
- const BooleanProperty = (config = {}, additionalMetadata={}) => Property(
269
- PROPERTY_TYPES.BooleanProperty,
270
- merge(config, {
271
- isBoolean: true,
272
- validators: _mergeValidators(config, [
273
- _getValidatorFromConfigElseEmpty(config, 'minValue', value =>
274
- minNumber(value)
275
- ),
276
- _getValidatorFromConfigElseEmpty(config, 'maxValue', value =>
277
- maxNumber(value)
278
- ),
279
- ]),
280
- }),
281
- additionalMetadata
282
- )
283
-
284
- const UniqueId = (config = {}, additionalMetadata={}) =>
285
- Property(
286
- PROPERTY_TYPES.UniqueId,
287
- {
288
- ...config,
289
- lazyLoadMethod: value => {
290
- if (!value) {
291
- return createUuid()
292
- }
293
- return value
294
- },
295
- }, additionalMetadata)
296
-
297
-
298
-
299
- module.exports = {
300
- Property,
301
- UniqueId,
302
- DateProperty,
303
- ArrayProperty,
304
- ReferenceProperty,
305
- IntegerProperty,
306
- TextProperty,
307
- ConstantValueProperty,
308
- NumberProperty,
309
- ObjectProperty,
310
- EmailProperty,
311
- BooleanProperty,
312
- createPropertyTitle,
313
- }
@@ -1,50 +0,0 @@
1
- const { loweredTitleCase } = require('./utils')
2
-
3
- const SIZE_OF_GET = 'get'.length
4
- const IGNORABLE_KEYS = ['meta', 'functions']
5
-
6
- const _getValue = async value => {
7
- if (value === undefined) {
8
- return null
9
- }
10
- if (value === null) {
11
- return null
12
- }
13
- const type = typeof value
14
- if (type === 'function') {
15
- return _getValue(await value())
16
- }
17
- // Nested Json
18
- if (type === 'object' && value.functions && value.functions.toObj) {
19
- return _getValue(await value.functions.toObj())
20
- }
21
- // Dates
22
- if (type === 'object' && value.toISOString) {
23
- return _getValue(value.toISOString())
24
- }
25
- return value
26
- }
27
-
28
- const _getKey = key => {
29
- return key.startsWith('get') ? loweredTitleCase(key.slice(SIZE_OF_GET)) : key
30
- }
31
-
32
- const _shouldIgnoreKey = key => {
33
- return IGNORABLE_KEYS.includes(key)
34
- }
35
-
36
- const toObj = keyToFunc => async () => {
37
- return Object.entries(keyToFunc).reduce(async (acc, [key, value]) => {
38
- const realAcc = await acc
39
- if (_shouldIgnoreKey(key)) {
40
- return realAcc
41
- }
42
- const keyToUse = _getKey(key)
43
- const trueValue = await _getValue(value)
44
- return { ...realAcc, [keyToUse]: trueValue }
45
- }, Promise.resolve({}))
46
- }
47
-
48
- module.exports = {
49
- toObj,
50
- }