forked from jgskin/sequelize-i18n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
544 lines (432 loc) · 14.4 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
var _ = require('lodash');
class SequelizeI18N {
get options() {
return this.baseOptions;
}
// Get i18n table name from a base table name
getI18NName(modelName) {
return `${modelName}${this.baseOptions.suffix}`;
}
getLanguageArrayType() {
let isNumber = true;
const arr = this.baseOptions.languages;
for (let index = 0; index < arr.length; index += 1) {
if (typeof arr[index] !== 'number') {
isNumber = false;
break;
}
}
return isNumber ? 'INTEGER' : 'STRING';
}
getModelUniqueKey(model) {
let pk = _.filter(model, obj => obj.primaryKey === true);
if (!(pk && pk.length)) pk = _.filter(model, obj => obj.unique === true);
pk = pk[0] || null;
return pk;
}
toArray(obj) {
if (obj) {
if (Array.isArray(obj)) return obj;
return [obj];
}
return [];
}
constructor(sequelize, options) {
var defaultOptions = {
i18nDefaultScope : true,
addI18NScope : true,
injectI18NScope : true,
suffix: '_i18n',
};
this.baseOptions = _.assign({}, defaultOptions, options);
this.excludedAttributes = ["id", "parent_id"];
if (!(
this.baseOptions.languages &&
Array.isArray(this.baseOptions.languages) &&
this.baseOptions.languages.length &&
this.baseOptions.defaultLanguage
)) {
throw new Error('Language list and default language are mandatory and can\'t be empty');
}
if (this.baseOptions.defaultLanguage && this.baseOptions.languages.indexOf(this.baseOptions.defaultLanguage) == -1) {
throw new Error('Default language is invalid');
}
const key = this.getLanguageArrayType();
sequelize.options.i18nOptions = this.baseOptions;
this.sequelize = sequelize;
this.languageType = sequelize.Sequelize[key];
this.i18nModels = {};
}
init() {
this.beforeDefine();
this.afterDefine();
}
// Create and define a new i18n model
createI18NModel(name, attributes, options, baseModelName) {
if (!attributes) throw new Error('Could not create i18n model without attributes');
this.sequelize.define(name, attributes, options);
return {
base: {
name,
defined: true,
model: attributes,
},
target: {
name: baseModelName,
defined: false,
},
};
}
getFormattedInclude(modelName){
const model = this.sequelize.models[modelName];
return {
model: model,
//limit: 1,
as: model.name,
attributes: {
exclude: this.excludedAttributes,
},
}
}
// Add i18n in base model default scope
setDefaultScope(defaultScope, name) {
if (!name) return defaultScope;
const mutableDefaultScope = defaultScope;
const defInclude= this.getFormattedInclude(name);
mutableDefaultScope.include = this.toArray(mutableDefaultScope.include);
mutableDefaultScope.include.push(defInclude);
return null;
}
// Inject i18n in base model user defined scopes
injectI18NScope(scopes, name) {
const mutableScopes = scopes;
Object.keys(mutableScopes).forEach((scope) => {
mutableScopes[scope].include = this.toArray(mutableScopes[scope].include);
mutableScopes[scope].include.push(this.getFormattedInclude(name));
});
}
// Add i18n in base model scopes
addI18NScope(scopes, name) {
const mutableScopes = scopes;
const include = this.getFormattedInclude(name);
//filter on language
mutableScopes.i18n = function (language_id) {
console.log('i18N scope has been invoked with language ', language_id);
if(language_id)
return {
include,
where:{ language_id }
}
return {
include
}
};
}
// Define model instance methods
setInstanceMethods(baseInstanceMethods, i18nModelName) {
const mutableBaseInstanceMethods = baseInstanceMethods;
mutableBaseInstanceMethods.setI18N = this.setI18N(i18nModelName);
mutableBaseInstanceMethods.getI18N = this.getI18N(i18nModelName);
}
afterCreate(instance, options) {
const i18nModel = this.i18nModel;
if (i18nModel === null) return;
const i18nOptions = {};
const baseOptions = this.sequelize.options.i18nOptions || {};
if (instance && instance.dataValues && i18nModel.model) {
Object.keys(instance.dataValues).forEach((prop) => {
if (prop in i18nModel.model) i18nOptions[prop] = instance.dataValues[prop];
});
i18nOptions.language_id = options.language_id || baseOptions.defaultLanguage;
i18nOptions.parent_id = instance.dataValues.id;
}
return this
.sequelize
.models[i18nModel.name]
.findOrCreate({
where: {
language_id: i18nOptions.language_id,
parent_id: i18nOptions.parent_id,
},
// TODO: probably a bad key mapping here.
defaults: i18nOptions,
})
.then(() => {
return instance.reload();
})
.catch(error => {
return instance.destroy({ force: true }).then(() => {
throw error;
});
});
}
afterDefine() {
this.sequelize.afterDefine('afterDefine_i18n', (model) => {
if (this.i18nModels[model.name]) {
const i18nModel = this.i18nModels[model.name].base;
const i18nRealModel = this.sequelize.models[i18nModel.name];
if(i18nModel) {
model.i18nModel = i18nModel;
model.i18n = i18nRealModel;
this.sequelize.models[model.name].hasMany( i18nRealModel, {
as: i18nRealModel.name,
foreignKey: 'parent_id',
unique: 'i18n_unicity_constraint',
});
model.addHook('beforeFind','addLanguage_i18n', this.addLanguage);
model.addHook('beforeFind','beforeFind_i18n', this.beforeFind);
model.addHook('afterCreate','afterCreate_i18n', this.afterCreate);
model.addHook('afterUpdate','afterUpdate_i18n', this.afterUpdate);
model.addHook('afterDestroy','afterDelete_i18n', this.afterDelete);
//add ability to add a translation for another language
model.prototype.addI18N = function (newValues, languageID) {
const instance = this;
const model = this.sequelize.models[this.constructor.name];
const i18nModel = model.i18nModel;
const baseOptions = this.sequelize.options.i18nOptions || {};
if (!newValues || !i18nModel || !languageID || !baseOptions || !_.includes(baseOptions.languages, languageID)) return;
const i18nOptions = {
language_id: languageID,
parent_id: instance.id,
};
const whereClause = _.assign(i18nOptions);
if (i18nModel.model) {
Object.keys(newValues).forEach((prop) => {
if (prop in i18nModel.model) i18nOptions[prop] = newValues[prop];
});
}
return this
.sequelize
.models[i18nModel.name]
.findOrCreate({
where: whereClause,
defaults: i18nOptions,
})
.then(() => instance.reload({
language_id: languageID
}));
};
//add ability to remove a translation for another language
model.prototype.deleteI18N = function (languageID) {
const instance = this;
if (!languageID) return;
return this
.sequelize
.models[i18nModel.name]
.destroy({
where: {
language_id: languageID,
parent_id: instance.id,
}
});
};
//add ability to remove a translation for another language
model.prototype.getI18N = function (languageID) {
const model = this.sequelize.models[this.constructor.name];
const i18nModel = model.i18nModel;
if(!i18nModel) return
return _.find(this[i18nModel.name],['language_id', languageID]);
};
}
}
});
}
afterDelete(instance, options, fn) {
const i18nModel = this.i18nModel;
if (i18nModel === null) return;
return this
.sequelize
.models[i18nModel.name]
.destroy({
where: {
parent_id: instance.id,
},
});
}
afterUpdate(instance, options) {
const i18nModel = this.i18nModel;
if (i18nModel === null) return;
const i18nOptions = {};
const baseOptions = this.sequelize.options.i18nOptions || {};
if (instance && instance.dataValues && i18nModel.model) {
Object.keys(instance.dataValues).forEach((prop) => {
if (prop in i18nModel.model) i18nOptions[prop] = instance.dataValues[prop];
});
i18nOptions.language_id = options.language_id || baseOptions.defaultLanguage;
i18nOptions.parent_id = instance.dataValues.id;
}
return this
.sequelize
.models[i18nModel.name]
.update(i18nOptions, {where: {
parent_id: i18nOptions.parent_id,
language_id: i18nOptions.language_id,
}})
.then(() => instance.reload());
}
beforeDefine() {
this.sequelize.beforeDefine('beforeDefine_i18n', (model, options) => {
const mutableModel = model;
const mutableOptions = options;
const baseOptions = {
indexes: [],
paranoid: mutableOptions.paranoid,
timestamps: mutableOptions.timestamps,
underscored: mutableOptions.i18n? (mutableOptions.i18n.underscored && true): true,
};
const pk = this.getModelUniqueKey(mutableModel);
let schema = null;
Object.keys(mutableModel).forEach((prop) => {
if ('i18n' in mutableModel[prop] && (mutableModel[prop].i18n === true)) {
if (!pk) {
throw new Error(`No primary or unique key found for ${mutableOptions.modelName} model`);
}
schema = schema || {
language_id: {
type: this.languageType,
unique: 'i18n_unicity_constraint',
},
parent_id: {
type: pk.type,
unique: 'i18n_unicity_constraint',
},
};
//if paranoid mode, the deleted element stays in the DB so we need to add the field deletedAt to the unique key (field created by using paranoid)
if(mutableOptions.paranoid == true)
schema.deleteAt = {
type: this.sequelize.Sequelize.DATE,
unique: 'i18n_unicity_constraint',
};
if ('unique' in mutableModel[prop] && (mutableModel[prop].unique === true)) {
baseOptions.indexes.push({
unique: true,
fields: mutableOptions.paranoid == true ? ['language_id', 'deletedAt', prop]: ['language_id', prop],
});
}
schema[prop] = {
type: mutableModel[prop].type,
};
mutableModel[prop].type = this.sequelize.Sequelize.VIRTUAL;
//add a VIRTUAL field for language_id to be added to the FIND queries
if(!mutableModel.language_id || mutableModel.language_id.type != this.sequelize.Sequelize.VIRTUAL){
mutableModel.language_id = {
type: this.sequelize.Sequelize.VIRTUAL
};
}
}
});
if (schema) {
const name = this.getI18NName(mutableOptions.modelName);
const createdModel = this.createI18NModel(
name,
schema,
baseOptions,
mutableOptions.modelName,
);
this.i18nModels[mutableOptions.modelName] = createdModel;
if (this.baseOptions.i18nDefaultScope) {
mutableOptions.defaultScope = mutableOptions.defaultScope || {};
this.setDefaultScope(mutableOptions.defaultScope, name);
}
if (this.baseOptions.addI18NScope) {
mutableOptions.scopes = mutableOptions.scopes || {};
this.addI18NScope(mutableOptions.scopes, name);
}
if (this.baseOptions.injectI18NScope) {
mutableOptions.scopes = mutableOptions.scopes || {};
this.injectI18NScope(mutableOptions.scopes, name);
}
mutableOptions.instanceMethods = mutableOptions.instanceMethods || {};
this.setInstanceMethods(mutableOptions.instanceMethods, name);
}
});
}
addLanguage(options) {
const mutableOptions = options;
//add the language value to the virtual field if provided so it can be used by each instances returned
if(this.rawAttributes.language_id &&
this.rawAttributes.language_id.type == 'VIRTUAL' &&
(mutableOptions.language_id || (mutableOptions.where && mutableOptions.where.language_id))) {
if(!mutableOptions.attributes)
mutableOptions.attributes = [...Object.keys(this.tableAttributes)];
const locale = mutableOptions.language_id || mutableOptions.where.language_id;
mutableOptions.attributes.push([this.sequelize.literal('\'' + locale + '\''), 'language_id']);
}
}
beforeFind(options) {
const mutableOptions = options;
const i18nModel = this.i18nModel;
if (mutableOptions && mutableOptions.where && i18nModel) {
Object.keys(mutableOptions.where).forEach((prop) => {
if (prop in i18nModel.model) {
mutableOptions.include = mutableOptions.include || [];
mutableOptions.include.forEach((incl) => {
const mutableIncl = incl;
if (mutableIncl.model.name === i18nModel.name) {
mutableIncl.where = mutableIncl.where || {};
mutableIncl.where[prop] = mutableOptions.where[prop];
}
});
delete mutableOptions.where[prop];
}
if (Array.isArray(mutableOptions.where[prop])) {
mutableOptions.include = mutableOptions.include || [];
mutableOptions.include.forEach((incl) => {
const mutableIncl = incl;
if (mutableIncl.model.name === i18nModel.name) {
mutableIncl.where = mutableIncl.where || {};
mutableIncl.where[prop] = mutableOptions.where[prop];
}
});
delete mutableOptions.where[prop];
}
});
}
if (mutableOptions && mutableOptions.order && i18nModel) {
mutableOptions.order.forEach((prop, index) => {
if (prop[0] in i18nModel.model) {
mutableOptions.order[index] = [{
model: this.sequelize.models[i18nModel.name],
as: i18nModel.name,
}, prop[0], prop[1]];
}
});
}
}
getI18N(modelName) {
return (lang) => {
let exit = false;
if (this.baseOptions.defaultLanguage === null) exit = true;
// TODO: model name is not defined as this in the instance which can break the whole library.
if (!(this[modelName] && this[modelName].length) || exit) return this;
for (let index = 0; index < this[modelName].length; index += 1) {
const value = this[modelName][index].toJSON();
if (value.language_id && value.language_id === lang) {
exit = true;
Object.keys(value).forEach((prop) => {
if (prop !== 'language_id' && prop !== 'parent_id' && prop !== 'id') {
this[prop] = value[prop];
}
});
}
}
return this;
};
}
setI18N(modelName) {
return (lang, propertyName, value, callback) => {
if (!lang && !this.baseOptions.defaultLanguage) throw new Error('No language given');
if (!propertyName) throw new Error('Property name to update is missing');
const currentObjectID = this.id;
const options = {
parent_id: currentObjectID,
language_id: lang,
};
options[propertyName] = value;
this.sequelize.models[modelName].upsert(options).then((result) => {
if (callback && (typeof callback === 'function')) callback(result);
});
};
}
}
module.exports = SequelizeI18N;