-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
259 lines (223 loc) · 8.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
const dot = require('dot-object');
const deepmerge = require('deepmerge');
const DEFAULT_PROVIDERS = require('./src/default-pipeline');
const TypeCast = require('./src/TypeCastProvider');
module.exports = {
translateObject,
translateValue,
translateList,
};
/**
* Checks if a JSON Schema has the required conditions to be translatable from another object
* @param {object} propertySchema JSON Schema
*/
function _isTransleatable(propertySchema) {
return propertySchema.from
|| (propertySchema.translation && propertySchema.translation.from)
|| propertySchema.default;
}
/**
* Translates an object given a JSON Schema with translation specification.
* @param {object} sourceObject The object to be translated.
* @param {object} targetSchema The JSON Schema containing translation specification.
* @param {object} [options={}] Translation default options to use in each property translation.
* @returns
*/
async function translateObject(sourceObject, targetSchema, options = {}) {
const logger = options.logger || console.log;
const methodOptions = options;
let providers = DEFAULT_PROVIDERS;
if (options.providers) {
providers = [...DEFAULT_PROVIDERS, ...options.providers];
}
const schemas = options.schemas || [];
const schemaOptions = deepmerge(methodOptions, targetSchema.translation || {});
const newObjectResult = {};
// TODO: deep schema translation
for (const targetKey in targetSchema.properties) {
const targetPropertySchema = targetSchema.properties[targetKey];
const { translation } = targetPropertySchema;
if (_isTransleatable(targetPropertySchema)) {
const sourceKey = targetPropertySchema.from || (translation && translation.from) || '';
const propertyOptions = deepmerge(schemaOptions, targetPropertySchema.translation || {});
let currentValue;
if (sourceKey !== '') {
currentValue = dot.pick(sourceKey, sourceObject) || undefined;
}
if (typeof currentValue === 'undefined' && targetPropertySchema.default) {
currentValue = targetPropertySchema.default;
}
let value = await translateValue(currentValue, targetPropertySchema, {
schemas,
methodOptions,
sourceKey,
sourceObject,
targetSchema,
providers,
logger,
options: propertyOptions,
targetKey,
});
if (typeof value === 'undefined' && targetPropertySchema.default) {
value = targetPropertySchema.default;
}
newObjectResult[targetKey] = value;
}
}
return newObjectResult;
}
/**
* Translates an object given a JSON Schema with translation specification.
* @param {object} sourceObjectList The list of objects to be translated.
* @param {object} targetSchema The JSON Schema containing translation specification.
* @param {object} [options={}] Translation default options to use in each property translation.
* @returns
*/
async function translateList(sourceObjectList, targetSchema, options = {}) {
const objectList = [];
for (const sourceObject of sourceObjectList) {
const objectResult = await translateObject(sourceObject, targetSchema, options);
objectList.push(objectResult);
}
return objectList;
}
/**
* Sort a list of translation providers by convert a sortered list of strings.
* @param {string[]} keys The list containing providers' names or collection names (collections must be prefixed with '#').
* @param {object[]} providers List of providers objects.
* @returns {object[]} List of sorted providers objects.
*/
function _pipelineKeysToProviders(keys, providers) {
return keys
.map((stepName) => {
let steps;
if (stepName.startsWith('#')) {
steps = providers.filter(p => p.collection === stepName.replace('#', ''));
} else {
steps = providers.find(p => p.name === stepName);
}
return steps;
})
.reduce((a, b) => [...a, ...(!b.length ? [b] : b) ], []);
}
/**
* Determines the execution list of providers and its order based on property options.
* @param {object} propertyOptions Options that may include a 'pipeline' property.
* @param {object[]} providers List of providers to be selected and sorted.
* @returns
*/
function _determinePipelineExecution(propertyOptions, providers) {
if (typeof propertyOptions.pipeline === 'object' && propertyOptions.pipeline.length) {
return _pipelineKeysToProviders(propertyOptions.pipeline, providers);
} else if (typeof propertyOptions.pipeline === 'object') {
let startPipeline = [];
let middlePipeline = providers;
let endPipeline = [];
if (propertyOptions.start) {
startPipeline = _pipelineKeysToProviders(propertyOptions.start, providers);
middlePipeline = providers.filter(p => {
return !propertyOptions.start.includes(p.name)
&& !propertyOptions.start.includes(`#${p.collection}`);
});
}
if (propertyOptions.end) {
endPipeline = _pipelineKeysToProviders(propertyOptions.start, middlePipeline);
middlePipeline = middlePipeline.filter(p => {
return !propertyOptions.end.includes(p.name)
&& !propertyOptions.end.includes(`#${p.collection}`);
});
}
return [...startPipeline, ...middlePipeline, ...endPipeline];
}
return providers;
}
function _typecastStartOrBoth(typecastOption) {
return typecastOption
&& typecastOption !== 'off'
&& (typecastOption === 'start' || typecastOption === 'both');
}
function _typecastEndOrBoth(typecastOption) {
return typecastOption
&& typecastOption !== 'off'
&& (typecastOption === 'end' || typecastOption === 'both');
}
function _anyProviderRequiresTypecastOnStart(providers, ) {
return providers.find(provider => provider.typecast && _typecastStartOrBoth(provider.typecast))
}
function _anyProviderRequiresTypecastOnEnd(providers, ) {
return providers.find(provider => provider.typecast && _typecastEndOrBoth(provider.typecast))
}
function _anyProviderDisablesTypecast(providers, ) {
return providers.find(provider => provider.typecast && provider.typecast === 'off')
}
/**
* Translates a value given a JSON Schema with translation specification.
* @param {*} currentValue Value to be translated.
* @param {*} targetPropertySchema JSON Schema containing translation specification.
* @param {*} {
* sourceKey,
* sourceObject,
* targetSchema,
* providers,
* options,
* } translateValueOptions
* @param {string?} translateValueOptions.sourceKey The property key of source object corresponding to currentValue.
* @param {object?} translateValueOptions.sourceObject The source object which the currentValue was obtained from.
* @param {object?} translateValueOptions.targetSchema The target schema which the targetPropertySchema was obtained from.
* @param {object[]} translateValueOptions.providers List of additional translation providers to be used.
* @param {object{}} translateValueOptions.options Additional translation options.
* @returns
*/
async function translateValue(currentValue, targetPropertySchema, {
targetKey,
sourceKey,
sourceObject,
targetSchema,
providers,
options,
schemas,
methodOptions,
}) {
const argumentsAsOptions = {
targetKey,
currentValue,
targetPropertySchema,
sourceKey,
sourceObject,
targetSchema,
providers,
options,
schemas,
methodOptions,
};
let value = currentValue;
const providersPipeline = _determinePipelineExecution(options, providers);
const providersToRun = providersPipeline.filter(p => p.shouldRun(argumentsAsOptions));
const typecastStart = _anyProviderRequiresTypecastOnStart(providersToRun);
const typecastEnd = _anyProviderRequiresTypecastOnEnd(providersToRun);
const typecastDisabled = _anyProviderDisablesTypecast(providersToRun);
if(typecastStart && typecastEnd) {
throw new Error('pipeline requires explicitly start or end together');
}
if ((typecastStart && typecastDisabled) || (typecastEnd && typecastDisabled)) {
throw new Error('pipeline both disables and requires typecast');
}
if (!typecastDisabled
&& !typecastEnd
&& (typeof options.typecast === 'undefined'
|| _typecastStartOrBoth(options.typecast)
|| typecastStart)
&& TypeCast.shouldRun(argumentsAsOptions)) {
value = await TypeCast.getValue(value, targetPropertySchema, argumentsAsOptions);
}
for (let i = 0; i < providersToRun.length; i++) {
const provider = providersToRun[i];
value = await provider.getValue(value, targetPropertySchema, argumentsAsOptions);
}
if (!typecastDisabled
&& ((options.typecast && _typecastEndOrBoth(options.typecast)) || typecastEnd)
&& TypeCast.shouldRun(argumentsAsOptions)) {
value = await TypeCast.getValue(value, targetPropertySchema, argumentsAsOptions);
}
return value;
}