@digione/node-custom-api 0.1.9 → 0.2.0-alpha10

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.
package/utils/file.js CHANGED
@@ -14,7 +14,6 @@ const aws = require("aws-sdk");
14
14
  const jimp = require("jimp/dist");
15
15
  const mime = require("mime-types");
16
16
  const _ = require("lodash");
17
- const uuid_1 = require("uuid");
18
17
  const path = require("path");
19
18
  const fs = require("fs");
20
19
  const getBuffer = (image, { mimetype = "" } = {}) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
@@ -108,6 +107,7 @@ class FileUtil {
108
107
  }
109
108
  afterQueryFile(data = {}, { tag = {}, file_link = false } = {}) {
110
109
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
110
+ delete data['thumbnail'];
111
111
  data['custom'] = data['custom'] || {};
112
112
  data['tags'] = data['tags'] || [];
113
113
  if (data['filename'] == data['path']) {
@@ -133,6 +133,7 @@ class FileUtil {
133
133
  let reqs = [], results = [];
134
134
  for (let file of files) {
135
135
  let extension = mime.extension(file.mimetype);
136
+ extension = extension ? extension : String(file.mimetype).split('/')[1];
136
137
  let input = {
137
138
  Bucket: this.bucket,
138
139
  Key: this.ref + "/" + (0, helper_1.getDateTime)().format('X') + '.' + (0, helper_1.getSlug)(32) + '.' + extension,
@@ -256,7 +257,7 @@ class FileUtil {
256
257
  result[width + 'x' + height] = thumb;
257
258
  yield (0, db_1.update)(this.ref, file_1.FileModel.getTableName().toString(), { thumb: JSON.stringify(result) }, { where: { id: item['id'] } });
258
259
  }
259
- if (item['filename'] == path) {
260
+ if (thumb && item['filename'] == path) {
260
261
  yield this.getStorage();
261
262
  let data = yield this.afterQueryFile({ filename: thumb, path: thumb });
262
263
  thumb = data.path;
@@ -275,12 +276,12 @@ class FileUtil {
275
276
  return null;
276
277
  where['$folder.parent_id$'] = query['id'];
277
278
  }
278
- where = this.beforeFindFile(where, { tags, group });
279
+ let option = this.beforeFindFile(where, { attributes: ['id', 'extension', 'filename', 'path', 'thumb'], tags, group });
279
280
  let result = yield file_1.FileModel.schema(this.ref, "_").findOne({
280
- raw: true, attributes: ['id', 'extension', 'filename', 'path', 'thumb'],
281
- where: Object.assign({ '$folder.slug$': slug }, where),
281
+ raw: true, attributes: option.attributes,
282
+ where: Object.assign({ '$folder.slug$': slug }, option.where),
282
283
  include: [{ as: 'folder', model: folder_1.FolderModel.schema(this.ref, "_"), attributes: [] }],
283
- order: [['sort', 'asc'], ['tags', 'desc']]
284
+ order: option.order
284
285
  });
285
286
  return this.findImageThumb(result, { width, height });
286
287
  }
@@ -298,7 +299,8 @@ class FileUtil {
298
299
  return this.findImageThumb(item, { width, height });
299
300
  });
300
301
  }
301
- beforeFindFile(where = {}, { tags = [], group = undefined } = {}) {
302
+ beforeFindFile(where = {}, { attributes = undefined, tags = [], group = undefined, verify = false } = {}) {
303
+ let order = [['sort', 'asc'], ['tags', 'desc']], thumbnail = false;
302
304
  if (this.option.organ_id) {
303
305
  where[sequelize_1.Op.and] = (where[sequelize_1.Op.and] || []).concat({ [sequelize_1.Op.or]: [{ organ_id: this.option.organ_id }, { organ_by: this.option.organ_id }] });
304
306
  }
@@ -309,9 +311,11 @@ class FileUtil {
309
311
  let op = tags.reduce((total, tag) => {
310
312
  let value = Object.keys(tag).reduce((total, key) => total.concat([`'${key}'`, `"${tag[key]}"`]), []).join(',');
311
313
  if (value) {
312
- total = total.concat((0, sequelize_1.literal)(`JSON_CONTAINS(tags,JSON_OBJECT(${value}))`));
313
- if (tag['slug'] == "thumbnail") {
314
- total = total.concat((0, sequelize_1.literal)(`tags IS NULL`));
314
+ if (tag['slug'] == "thumbnail" && !verify) {
315
+ thumbnail = true;
316
+ }
317
+ else {
318
+ total = total.concat((0, sequelize_1.literal)(`JSON_CONTAINS(tags,JSON_OBJECT(${value}))`));
315
319
  }
316
320
  }
317
321
  return total;
@@ -320,9 +324,19 @@ class FileUtil {
320
324
  where[sequelize_1.Op.and] = (where[sequelize_1.Op.and] || []).concat({ [sequelize_1.Op.or]: op });
321
325
  }
322
326
  }
323
- return where;
327
+ if (thumbnail) {
328
+ let include = [[(0, sequelize_1.literal)(`IF(JSON_CONTAINS(tags,JSON_OBJECT('slug',"thumbnail")),'yes','no')`), 'thumbnail']];
329
+ if (typeof attributes == "undefined") {
330
+ attributes = { include };
331
+ }
332
+ else if (attributes instanceof Array) {
333
+ attributes = attributes.concat(include);
334
+ }
335
+ order = [['thumbnail', 'desc'], ['sort', 'asc']];
336
+ }
337
+ return { where, attributes, order };
324
338
  }
325
- findAllFile({ where = {}, folder = false, full = false, file_link = false, thumb = false, width = 0, height = 0, parent_folder = "", attributes = undefined, limit = undefined, offset = undefined, tag = {}, tags = [], group = undefined } = {}) {
339
+ findAllFile({ where = {}, folder = false, full = false, file_link = false, thumb = false, verify = true, width = 0, height = 0, parent_folder = "", attributes = undefined, limit = undefined, offset = undefined, tag = {}, tags = [], group = undefined } = {}) {
326
340
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
327
341
  try {
328
342
  let include = [];
@@ -334,10 +348,10 @@ class FileUtil {
334
348
  return [];
335
349
  where['$folder.parent_id$'] = query['id'];
336
350
  }
337
- where = this.beforeFindFile(where, { tags, group });
338
351
  where['is_hidden'] = where['is_hidden'] || "no";
352
+ let option = this.beforeFindFile(where, { attributes, tags, group, verify });
339
353
  let result = yield file_1.FileModel.schema(this.ref, "_").findAll({
340
- attributes, raw: true, where, limit, offset, include, order: [['sort', 'asc'], ['tags', 'desc']]
354
+ attributes: option.attributes, raw: true, where: option.where, limit, offset, include, order: option.order
341
355
  });
342
356
  result.length && (yield this.getStorage());
343
357
  result = yield Promise.all(result.map((item) => tslib_1.__awaiter(this, void 0, void 0, function* () {
@@ -358,6 +372,33 @@ class FileUtil {
358
372
  }
359
373
  });
360
374
  }
375
+ countFileByFolder(slug, { where = {}, parent_folder = "", tags = [], group = null } = {}) {
376
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
377
+ let include_folder = [];
378
+ if (parent_folder) {
379
+ where['$`f->p`.slug$'] = parent_folder;
380
+ include_folder.push({
381
+ required: true, attributes: [],
382
+ model: folder_1.FolderModel.schema(this.ref, "_"),
383
+ association: new sequelize_1.BelongsTo(folder_1.FolderModel, folder_1.FolderModel, { as: "p", foreignKey: "parent_id", constraints: false })
384
+ });
385
+ }
386
+ where['$f.slug$'] = slug;
387
+ where['is_hidden'] = where['is_hidden'] || "no";
388
+ let option = this.beforeFindFile(where, { tags, group, verify: true });
389
+ return yield file_1.FileModel.schema(this.ref, "_").count({
390
+ where: option.where,
391
+ include: [
392
+ {
393
+ required: true, attributes: [],
394
+ model: folder_1.FolderModel.schema(this.ref, "_"),
395
+ association: new sequelize_1.BelongsTo(file_1.FileModel, folder_1.FolderModel, { as: "f", foreignKey: "folder_id", constraints: false }),
396
+ include: include_folder
397
+ }
398
+ ]
399
+ });
400
+ });
401
+ }
361
402
  findAndCountAllFileByFolder(slug, { where = {}, file_link = false, parent_folder = "", limit = undefined, offset = undefined, tag = {}, tags = [], group = null } = {}) {
362
403
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
363
404
  let where_folder = {};
@@ -371,9 +412,9 @@ class FileUtil {
371
412
  if (!folder)
372
413
  return { rows: [], count: 0 };
373
414
  where['folder_id'] = folder['id'];
374
- where = this.beforeFindFile(where, { tags, group });
375
415
  where['is_hidden'] = where['is_hidden'] || "no";
376
- let data = yield Promise.all([this.findAllFile({ where, full: true, file_link, limit, offset, tag, group }), file_1.FileModel.schema(this.ref, "_").count({ where })]);
416
+ let option = this.beforeFindFile(where, { tags, group, verify: true });
417
+ let data = yield Promise.all([this.findAllFile({ where, full: true, file_link, limit, offset, tag, group }), file_1.FileModel.schema(this.ref, "_").count({ where: option.where })]);
377
418
  return { rows: data[0], count: data[1] };
378
419
  });
379
420
  }
@@ -384,7 +425,7 @@ class FileUtil {
384
425
  }
385
426
  findOneFileByFolder(slug, { where = {}, full = false, file_link = false, parent_folder = "", tags = [], group = null } = {}) {
386
427
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
387
- return (yield this.findAllFile({ where: Object.assign({ '$folder.slug$': slug }, where), folder: true, full, file_link, parent_folder, limit: 1, tags, group }))[0] || null;
428
+ return (yield this.findAllFile({ where: Object.assign({ '$folder.slug$': slug }, where), folder: true, full, file_link, verify: false, parent_folder, limit: 1, tags, group }))[0] || null;
388
429
  });
389
430
  }
390
431
  findOneFileById(id, { where = {}, full = true, file_link = false, parent_folder = "", tags = [], group = null } = {}) {
@@ -392,7 +433,7 @@ class FileUtil {
392
433
  return (yield this.findAllFile({ where: Object.assign({ id }, where), full, file_link, parent_folder, limit: 1, tags, group }))[0] || null;
393
434
  });
394
435
  }
395
- uploadByReq(req, slug, user_id, { parent_id = 0, parent_slug = "", name = undefined, root = false, thumb = false, width = 0, height = 0, input = {}, is_hidden = undefined, tags = undefined, group = undefined } = {}) {
436
+ uploadByReq(req, slug, user_id, { parent_id = 0, parent_slug = "", name = undefined, root = false, format = false, thumb = false, width = 0, height = 0, input = {}, is_hidden = undefined, tags = undefined, group = undefined } = {}) {
396
437
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
397
438
  req.files = req.file ? [req.file] : (req.files || []);
398
439
  if (req.files.length && slug) {
@@ -406,6 +447,7 @@ class FileUtil {
406
447
  let folder = yield this.createFolder(slug, { parent_id, root, name });
407
448
  for (let file of req.files) {
408
449
  let extension = mime.extension(file.mimetype);
450
+ extension = extension ? extension : String(file.mimetype).split('/')[1];
409
451
  let input = {
410
452
  Bucket: this.bucket,
411
453
  Key: this.ref + "/" + (0, helper_1.getDateTime)().format('X') + '.' + (0, helper_1.getSlug)(32) + '.' + extension,
@@ -419,7 +461,7 @@ class FileUtil {
419
461
  }
420
462
  let results = yield this.upload(files);
421
463
  results = yield this.formatFile(folder['id'], user_id, reqs, results, { input, is_hidden, tags, group });
422
- return yield this.insertFileUnique(results, { thumb, width, height });
464
+ return yield this.insertFileUnique(results, { format, thumb, width, height });
423
465
  }
424
466
  return Promise.reject(errors_1.generalError.BAD_REQUEST);
425
467
  });
@@ -470,8 +512,13 @@ class FileUtil {
470
512
  let folder = yield this.createFolder(slug, { parent_id, root, name });
471
513
  let results = [], reqs = [];
472
514
  files.forEach((item) => {
473
- results.push({ Location: item, Key: item });
474
- reqs.push({ originalname: (0, helper_1.getSlug)(32), mimetype: null, size: 0, type });
515
+ let addition = {}, path = item;
516
+ if (typeof item == "object") {
517
+ addition = item;
518
+ path = item['path'];
519
+ }
520
+ results.push({ Location: path, Key: path });
521
+ reqs.push(Object.assign({ originalname: (0, helper_1.getSlug)(32), mimetype: null, size: 0, type }, addition));
475
522
  });
476
523
  results = yield this.formatFile(folder['id'], user_id, reqs, results, { input, tags, group });
477
524
  return yield this.insertFileUnique(results);
@@ -548,6 +595,8 @@ class FileUtil {
548
595
  case "shtml":
549
596
  case "svg":
550
597
  case "rar":
598
+ case "kml":
599
+ case "shp":
551
600
  type = 'o';
552
601
  break;
553
602
  }
@@ -557,12 +606,12 @@ class FileUtil {
557
606
  return type;
558
607
  });
559
608
  }
560
- formatFile(folder_id, user_id, reqs, files, { use_id = true, field = [], formatDateTime = "X", input = {}, is_hidden = undefined, tags = undefined, group = undefined } = {}) {
609
+ formatFile(folder_id, user_id, reqs, files, { format = false, use_id = true, field = [], formatDateTime = "X", input = {}, is_hidden = undefined, tags = undefined, group = undefined } = {}) {
561
610
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
562
611
  try {
563
612
  let result = yield Promise.all(files.map((file, key) => tslib_1.__awaiter(this, void 0, void 0, function* () {
564
613
  folder_id = reqs[key].folder ? reqs[key].folder : folder_id;
565
- let id = (0, uuid_1.v4)().replace(/-/gi, '').substring(0, 15);
614
+ let id = (0, helper_1.getFileId)();
566
615
  let organ_id = this.option.organ_id;
567
616
  let organ_by = this.option.parent_organ_id;
568
617
  let sort = (0, helper_1.getDateTime)().format(formatDateTime);
@@ -574,30 +623,30 @@ class FileUtil {
574
623
  path = (index < 0) ? protocol + path : path;
575
624
  }
576
625
  let extension = mime.extension(reqs[key].mimetype);
577
- let format = Object.assign(Object.assign({}, input), { folder_id,
626
+ extension = extension ? extension : String(reqs[key].mimetype).split('/')[1];
627
+ let item = Object.assign(Object.assign({}, input), { folder_id,
578
628
  user_id,
579
629
  organ_id,
580
- organ_by,
581
- sort,
582
- date_added, name: reqs[key].originalname || (0, helper_1.getSlug)(32), filename: reqs[key].Key || file.Key || input['filename'], path, mimetype: reqs[key].mimetype, filesize: reqs[key].size, extension: (extension ? "." + extension : ''), type: reqs[key].type || file.type || input['type'], is_hidden,
583
- tags,
584
- group });
630
+ organ_by, sort: reqs[key].sort || sort, date_added, name: reqs[key].originalname || (0, helper_1.getSlug)(32), filename: reqs[key].Key || file.Key || input['filename'], path, mimetype: reqs[key].mimetype, filesize: reqs[key].size, extension: (extension ? "." + extension : ''), type: reqs[key].type || file.type || input['type'], is_hidden, tags: reqs[key].tags || tags, custom: reqs[key].custom || input['custom'], group });
631
+ if (format) {
632
+ item = yield this.afterQueryFile(item);
633
+ }
585
634
  if (use_id) {
586
- format['id'] = id;
635
+ item['id'] = id;
587
636
  }
588
637
  if (reqs[key].mimetype && reqs[key].mimetype.split('/')[0] == "image") {
589
638
  try {
590
639
  let body = reqs[key].Body || reqs[key].buffer;
591
640
  let image = yield jimp.read(body);
592
- format['height'] = image.bitmap.height;
593
- format['width'] = image.bitmap.width;
641
+ item['height'] = image.bitmap.height;
642
+ item['width'] = image.bitmap.width;
594
643
  }
595
644
  catch (err) { }
596
645
  }
597
646
  if (field.length) {
598
- format = _.pick(format, field);
647
+ item = _.pick(item, field);
599
648
  }
600
- return format;
649
+ return item;
601
650
  })));
602
651
  return result;
603
652
  }
@@ -606,7 +655,7 @@ class FileUtil {
606
655
  }
607
656
  });
608
657
  }
609
- insertFileUnique(results, { thumb = false, width = 0, height = 0 } = {}) {
658
+ insertFileUnique(results, { format = false, thumb = false, width = 0, height = 0 } = {}) {
610
659
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
611
660
  try {
612
661
  let data = yield file_1.FileModel.schema(this.ref, "_").bulkCreate(results);
@@ -614,32 +663,31 @@ class FileUtil {
614
663
  return Promise.reject(errors_1.generalError.BAD_REQUEST);
615
664
  }
616
665
  let result = data.map(item => item.toJSON());
617
- if (thumb) {
618
- // create thumb
666
+ if (format || thumb) {
667
+ // format or create thumb
619
668
  result = yield Promise.all(result.map((item) => tslib_1.__awaiter(this, void 0, void 0, function* () {
620
- if (item['type'] == 'i') {
621
- item['thumb'] = null;
622
- let thumb = yield this.findImageThumb(item, { width, height });
623
- return Object.assign(Object.assign({}, item), { thumb });
669
+ let include = (yield this.afterQueryFile(item)) || {};
670
+ if (thumb && item['type'] == 'i') {
671
+ include['thumb'] = yield this.findImageThumb(item, { width, height });
624
672
  }
625
- return item;
673
+ return Object.assign(Object.assign({}, item), include);
626
674
  })));
627
675
  }
628
676
  return result;
629
677
  }
630
678
  catch (err) {
631
679
  if (err.errors && err.errors[0].validatorKey == "not_unique") {
632
- results = results.map(item => (Object.assign(Object.assign({}, item), { id: (0, uuid_1.v4)().replace(/-/gi, '').substring(0, 15) })));
633
- return yield this.insertFileUnique(results, { thumb, width, height });
680
+ results = results.map(item => (Object.assign(Object.assign({}, item), { id: (0, helper_1.getFileId)() })));
681
+ return yield this.insertFileUnique(results, { format, thumb, width, height });
634
682
  }
635
683
  return Promise.reject(errors_1.generalError.BAD_REQUEST);
636
684
  }
637
685
  });
638
686
  }
639
- uploadRawFormat(files, { field = ['name', 'filename', 'path', 'mimetype', 'filesize', 'extension', 'type', 'height', 'width'] } = {}) {
687
+ uploadRawFormat(files, { format = false, field = ['name', 'filename', 'path', 'mimetype', 'filesize', 'extension', 'type', 'height', 'width'] } = {}) {
640
688
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
641
689
  let query = yield this.uploadRaw(files);
642
- return yield this.formatFile(0, 0, files, query, { field });
690
+ return yield this.formatFile(0, 0, files, query, { format, field });
643
691
  });
644
692
  }
645
693
  updateFile(id, input = {}, { paths = [] } = {}) {
@@ -672,8 +720,8 @@ class FileUtil {
672
720
  }
673
721
  remove({ where = {}, delete_object = false, error = true, tags = [], group = undefined } = {}) {
674
722
  return tslib_1.__awaiter(this, void 0, void 0, function* () {
675
- where = this.beforeFindFile(where, { tags, group });
676
- let files = yield file_1.FileModel.schema(this.ref, "_").findAll({ where, attributes: ['id', 'path', 'thumb'], raw: true });
723
+ let option = this.beforeFindFile(where, { tags, group, verify: true });
724
+ let files = yield file_1.FileModel.schema(this.ref, "_").findAll({ where: option.where, attributes: ['id', 'path', 'thumb'], raw: true });
677
725
  if (files.length) {
678
726
  let paths = [], id = files.map(i => { paths = paths.concat(this.getFilePath(i)); return i['id']; });
679
727
  yield file_1.FileModel.schema(this.ref, "_").destroy({ where: { id } });
package/utils/helper.d.ts CHANGED
@@ -12,7 +12,12 @@ export declare const getDaysBetweenDates: (startDate: any, endDate: any, { utc }
12
12
  }) => any[];
13
13
  export declare const Joi_date: any;
14
14
  export declare const getENV: (str: string, def?: any) => any;
15
+ export declare const getENVIndex: (index: string, { prefix, force }?: {
16
+ prefix?: string;
17
+ force?: boolean;
18
+ }) => string;
15
19
  export declare const getSlug: (length?: number) => string;
20
+ export declare const getFileId: () => string;
16
21
  export declare const getDateMysql: (date?: any) => any;
17
22
  export declare const getTimestampMysql: (date?: any) => number;
18
23
  export declare const getDateTime: (time?: any, { utc }?: {
@@ -23,7 +28,12 @@ export declare const getValueFunctionFile: (key: any) => (value: any, { result,
23
28
  json?: {};
24
29
  fileUtil?: any;
25
30
  }) => Promise<void>;
26
- export declare const getValueFunctionLang: (key: any) => (value?: {}, { result, transform, spread, spread_all, raw, lang_code }?: {
31
+ export declare const getValueFunctionArray: (key: any) => (value: any, { result }: {
32
+ result?: {};
33
+ }) => void;
34
+ export declare const getValueFunctionLang: (key: any, { field_type }?: {
35
+ field_type?: string;
36
+ }) => (value?: {}, { result, transform, spread, spread_all, raw, lang_code }?: {
27
37
  result?: {};
28
38
  transform?: boolean;
29
39
  spread?: boolean;
@@ -50,6 +60,9 @@ export declare const removeHyphen: (str: string, replace?: string, { encode, rep
50
60
  export declare const getMobileNumber: (str: string, { prefix }?: {
51
61
  prefix?: string;
52
62
  }) => string;
63
+ export declare const formatMobileNumber: (str: string, { prefix }?: {
64
+ prefix?: string;
65
+ }) => string;
53
66
  export declare const removeSpace: (str: string, replace?: string) => string;
54
67
  export declare const removeAt: (str: string, replace?: string) => string;
55
68
  export declare const isNumber: (val: any, { negative }?: {
@@ -64,7 +77,7 @@ export declare const randomRef: ({ length_digital, length_alphabet }?: {
64
77
  length_alphabet?: number;
65
78
  }) => string;
66
79
  export declare const treeToArray: (items: Array<any>, array?: Array<any>, level?: number) => Promise<any[]>;
67
- export declare const buildTree: (nodes: Array<any>, { index, field_children, json_convert, key_index, key_parent, root, to_array }?: {
80
+ export declare const buildTree: (nodes: Array<any>, { index, field_children, json_convert, key_index, key_parent, root, to_array, notfound_parent }?: {
68
81
  index?: any;
69
82
  field_children?: string;
70
83
  json_convert?: boolean;
@@ -72,6 +85,7 @@ export declare const buildTree: (nodes: Array<any>, { index, field_children, jso
72
85
  key_parent?: string;
73
86
  root?: any;
74
87
  to_array?: boolean;
88
+ notfound_parent?: boolean;
75
89
  }) => Promise<any[]>;
76
90
  export declare const expandTree: (items: Array<any>, { array, parent, level, prefix, field_index, field_children, key_value }?: {
77
91
  array?: any[];
@@ -88,6 +102,7 @@ export declare const slugify: (string?: any, { lowercase }?: {
88
102
  }) => any;
89
103
  export declare const slugifyField: (string?: any) => any;
90
104
  export declare const stripHtml: (string: string) => string;
105
+ export declare const stripEmoji: (string: string) => string;
91
106
  export declare const replaceColon: (string: string, { decode }?: {
92
107
  decode?: boolean;
93
108
  }) => string;
package/utils/helper.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.convertCurrency = exports.xorMerge = exports.xorDecode = exports.xorEncode = exports.getInstanceNumber = exports.getDomain = exports.getParent = exports.replaceColon = exports.stripHtml = exports.slugifyField = exports.slugify = exports.convertToBigEndian = exports.expandTree = exports.buildTree = exports.treeToArray = exports.randomRef = exports.multiExecArray = exports.isBase64 = exports.isNumber = exports.removeAt = exports.removeSpace = exports.getMobileNumber = exports.removeHyphen = exports.signToken = exports.getTokenDataFromTokenBySecret = exports.getUUID32 = exports.getUUID = exports.sleep = exports.getValueByLang = exports.getValueFunctionLang = exports.getValueFunctionFile = exports.getDateTime = exports.getTimestampMysql = exports.getDateMysql = exports.getSlug = exports.getENV = exports.Joi_date = exports.getDaysBetweenDates = exports.getDateFromString = exports.getDateRangeFormat = void 0;
3
+ exports.convertCurrency = exports.xorMerge = exports.xorDecode = exports.xorEncode = exports.getInstanceNumber = exports.getDomain = exports.getParent = exports.replaceColon = exports.stripEmoji = exports.stripHtml = exports.slugifyField = exports.slugify = exports.convertToBigEndian = exports.expandTree = exports.buildTree = exports.treeToArray = exports.randomRef = exports.multiExecArray = exports.isBase64 = exports.isNumber = exports.removeAt = exports.removeSpace = exports.formatMobileNumber = exports.getMobileNumber = exports.removeHyphen = exports.signToken = exports.getTokenDataFromTokenBySecret = exports.getUUID32 = exports.getUUID = exports.sleep = exports.getValueByLang = exports.getValueFunctionLang = exports.getValueFunctionArray = exports.getValueFunctionFile = exports.getDateTime = exports.getTimestampMysql = exports.getDateMysql = exports.getFileId = exports.getSlug = exports.getENVIndex = exports.getENV = exports.Joi_date = exports.getDaysBetweenDates = exports.getDateFromString = exports.getDateRangeFormat = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const crypto = require("crypto");
6
6
  const dotenv = require("dotenv");
@@ -13,6 +13,7 @@ const date_1 = require("@joi/date");
13
13
  const numeral = require("numeral");
14
14
  const _ = require("lodash");
15
15
  const sha1 = require('js-sha1');
16
+ const uid = new short_unique_id_1.default();
16
17
  dotenv.config();
17
18
  const getDateRangeFormat = (dates = [], { format: { day = "D", month = "MMM", year = "Y" } = {} } = {}) => {
18
19
  dates = dates.map(i => (0, exports.getDateTime)(i));
@@ -57,10 +58,21 @@ const getENV = (str, def) => {
57
58
  return process.env[str] || def;
58
59
  };
59
60
  exports.getENV = getENV;
61
+ const getENVIndex = (index, { prefix = "dev", force = false } = {}) => {
62
+ if (process.env.NODE_ENV == "production" || force) {
63
+ return index;
64
+ }
65
+ return prefix + "_" + index;
66
+ };
67
+ exports.getENVIndex = getENVIndex;
60
68
  const getSlug = (length = 8) => {
61
- return new short_unique_id_1.default().randomUUID(length);
69
+ return uid.rnd(length);
62
70
  };
63
71
  exports.getSlug = getSlug;
72
+ const getFileId = () => {
73
+ return uid.rnd(15);
74
+ };
75
+ exports.getFileId = getFileId;
64
76
  const getDateMysql = (date = undefined) => {
65
77
  try {
66
78
  return (0, exports.getDateTime)(date).format("YYYY-MM-DD HH:mm:ss");
@@ -94,7 +106,22 @@ const getValueFunctionFile = (key) => {
94
106
  });
95
107
  };
96
108
  exports.getValueFunctionFile = getValueFunctionFile;
97
- const getValueFunctionLang = (key) => {
109
+ const getValueFunctionArray = (key) => {
110
+ return (value, { result = {} }) => {
111
+ if (value[key]) {
112
+ try {
113
+ result[key] = JSON.parse(value[key]);
114
+ }
115
+ catch (err) { }
116
+ ;
117
+ }
118
+ if (!(result[key] instanceof Array)) {
119
+ result[key] = [];
120
+ }
121
+ };
122
+ };
123
+ exports.getValueFunctionArray = getValueFunctionArray;
124
+ const getValueFunctionLang = (key, { field_type = "" } = {}) => {
98
125
  return (value = {}, { result = {}, transform = true, spread = false, spread_all = false, raw = false, lang_code = "" } = {}) => {
99
126
  if (raw || typeof value[key] == "undefined")
100
127
  return;
@@ -118,6 +145,9 @@ const getValueFunctionLang = (key) => {
118
145
  return;
119
146
  }
120
147
  result[key] = bol ? (obj[lang_code] || obj['en']) : value[key];
148
+ if (field_type == "stream") {
149
+ (0, exports.getValueFunctionArray)(key)({ [key]: result[key] }, { result });
150
+ }
121
151
  };
122
152
  };
123
153
  exports.getValueFunctionLang = getValueFunctionLang;
@@ -154,14 +184,25 @@ exports.removeHyphen = removeHyphen;
154
184
  const getMobileNumber = (str, { prefix = "+66" } = {}) => {
155
185
  if (str) {
156
186
  str = str.replace(/_/g, "").replace(/-/g, "").replace(/ /g, "");
157
- if (str.indexOf("+") == -1 && str.length == 10) {
158
- str = str.substr(1);
187
+ if (str.indexOf("+") == -1 && (str.length == 10 || str.length == 9)) {
188
+ if (str.length == 10 && str[0] == "0")
189
+ str = str.substr(1);
159
190
  str = prefix + str;
160
191
  }
161
192
  }
162
193
  return str;
163
194
  };
164
195
  exports.getMobileNumber = getMobileNumber;
196
+ const formatMobileNumber = (str, { prefix = "+66" } = {}) => {
197
+ if (str) {
198
+ str = str.replace(/_/g, "").replace(/-/g, "").replace(/ /g, "").replace(prefix, "");
199
+ if (str.length == 9) {
200
+ str = "0" + str;
201
+ }
202
+ }
203
+ return str;
204
+ };
205
+ exports.formatMobileNumber = formatMobileNumber;
165
206
  const removeSpace = (str, replace = "") => {
166
207
  return str ? str.replace(/ /g, replace) : "";
167
208
  };
@@ -228,7 +269,7 @@ const treeToArray = (items, array = [], level = 1) => tslib_1.__awaiter(void 0,
228
269
  return array;
229
270
  });
230
271
  exports.treeToArray = treeToArray;
231
- const buildTree = (nodes, { index = undefined, field_children = "children", json_convert = false, key_index = "id", key_parent = "parent", root = undefined, to_array = false } = {}) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
272
+ const buildTree = (nodes, { index = undefined, field_children = "children", json_convert = false, key_index = "id", key_parent = "parent", root = undefined, to_array = false, notfound_parent = false } = {}) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
232
273
  if (!nodes) {
233
274
  return null;
234
275
  }
@@ -266,11 +307,16 @@ const buildTree = (nodes, { index = undefined, field_children = "children", json
266
307
  }
267
308
  }
268
309
  parent[field_children] = results;
310
+ delete children[parent[key_index]];
269
311
  }
270
312
  };
271
313
  for (let i = 0, len = roots.length; i < len; ++i) {
272
314
  findChildren(roots[i]);
273
315
  }
316
+ if (notfound_parent) {
317
+ let items = Object.keys(children).reduce((total, key) => total.concat(children[key]), []);
318
+ roots.unshift({ [key_index]: -1, [field_children]: items });
319
+ }
274
320
  if (index)
275
321
  roots = roots[0];
276
322
  if (roots && to_array) {
@@ -350,6 +396,10 @@ const stripHtml = (string) => {
350
396
  .replace(/\n/g, '');
351
397
  };
352
398
  exports.stripHtml = stripHtml;
399
+ const stripEmoji = (string) => {
400
+ return String(string).replace(/(?![*#0-9]+)[\p{Emoji}\p{Emoji_Modifier}\p{Emoji_Component}\p{Emoji_Modifier_Base}\p{Emoji_Presentation}]/gu, '').trim();
401
+ };
402
+ exports.stripEmoji = stripEmoji;
353
403
  const replaceColon = (string, { decode = false } = {}) => {
354
404
  if (!string || typeof (string) != 'string') {
355
405
  return string;
package/utils/metadata.js CHANGED
@@ -27,11 +27,11 @@ class MetadataUtil {
27
27
  let value = {}, type = types;
28
28
  if (_.isObject(input[key])) {
29
29
  let val = {};
30
- _.each(input[key], (v, k) => { val['value_' + k] = (0, helper_1.stripHtml)(v ? v.substring(0, str_length) : ""); });
30
+ _.each(input[key], (v, k) => { val['value_' + k] = v ? (0, helper_1.stripEmoji)((0, helper_1.stripHtml)(v)).substring(0, str_length) : ""; });
31
31
  value = val;
32
32
  }
33
33
  else {
34
- value = { value_en: (0, helper_1.stripHtml)(String(input[key] || "").substring(0, str_length)) };
34
+ value = { value_en: (0, helper_1.stripEmoji)((0, helper_1.stripHtml)(String(input[key] || "")).substring(0, str_length)) };
35
35
  }
36
36
  if (autoType && !items[key]) {
37
37
  let str = key.split(":");
package/utils/stream.d.ts CHANGED
@@ -40,7 +40,7 @@ export declare class StreamUtil {
40
40
  private fileUtil;
41
41
  private languageUtil;
42
42
  constructor(ref?: string, option?: QueryParamOption, fileUtil?: FileUtil);
43
- findField(slug: string, namespace: string, { index, option, no_lang, field_slug, field_only, field_required, lang, lang_code, is_required, default_value, addition, include, include_only, convert_option, field_option, require, multiple_table, multiple_spread, text, bullets, multiple, relationship, file, image, field_exclude, section }?: {
43
+ findField(slug: string, namespace: string, { index, option, no_lang, field_slug, field_only, field_required, lang, lang_code, is_required, default_value, addition, include, include_only, convert_option, convert_value, field_option, require, multiple_table, multiple_spread, text, bullets, multiple, relationship, file, image, field_exclude, section }?: {
44
44
  index?: string;
45
45
  option?: {};
46
46
  no_lang?: boolean;
@@ -55,6 +55,7 @@ export declare class StreamUtil {
55
55
  include?: any;
56
56
  include_only?: boolean;
57
57
  convert_option?: boolean;
58
+ convert_value?: boolean;
58
59
  field_option?: {};
59
60
  require?: boolean;
60
61
  multiple_table?: boolean;
@@ -75,13 +76,14 @@ export declare class StreamUtil {
75
76
  include?: any;
76
77
  include_only?: boolean;
77
78
  }): any;
78
- buildStream(slug: string, namespace: string, { query, builder, fetch, label, attribute, attributes, field_exclude, include, include_all }?: {
79
+ buildStream(slug: string, namespace: string, { query, builder, fetch, label, attribute, attributes, field_option, field_exclude, include, include_all }?: {
79
80
  query?: boolean;
80
81
  builder?: boolean;
81
82
  fetch?: boolean;
82
83
  label?: boolean;
83
84
  attribute?: boolean;
84
85
  attributes?: any;
86
+ field_option?: {};
85
87
  field_exclude?: any[];
86
88
  include?: {};
87
89
  include_all?: boolean;
@@ -91,10 +93,11 @@ export declare class StreamUtil {
91
93
  fetchFn: any;
92
94
  attributes: any;
93
95
  }>;
94
- getBuilder(slug: string, namespace: string, { query, index, builder, field_exclude }?: {
96
+ getBuilder(slug: string, namespace: string, { query, index, builder, field_option, field_exclude }?: {
95
97
  query?: boolean;
96
98
  index?: string;
97
99
  builder?: boolean;
100
+ field_option?: {};
98
101
  field_exclude?: any[];
99
102
  }): Promise<any>;
100
103
  getValue(slug: string, namespace: string, value: any, { query, transform, spread, spread_all, raw, lang_code }?: {
@@ -117,7 +120,7 @@ export declare class StreamUtil {
117
120
  result: {};
118
121
  labels: any[];
119
122
  }>;
120
- genField(streams: Array<any>, { index, option, slug, id_stream, prefix, multiple_table, multiple_spread, addition, convert_option, field_option, default_value, default_lang, lang_code, no_lang, lang, country, section }?: {
123
+ genField(streams: Array<any>, { index, option, slug, id_stream, prefix, multiple_table, multiple_spread, addition, convert_option, convert_value, field_option, default_value, default_lang, lang_code, no_lang, lang, country, section }?: {
121
124
  index?: string;
122
125
  option?: {};
123
126
  slug?: string;
@@ -127,6 +130,7 @@ export declare class StreamUtil {
127
130
  multiple_spread?: boolean;
128
131
  addition?: {};
129
132
  convert_option?: boolean;
133
+ convert_value?: boolean;
130
134
  field_option?: {};
131
135
  default_value?: any;
132
136
  default_lang?: string;
@@ -168,6 +172,14 @@ export declare class StreamUtil {
168
172
  tags?: TagFile;
169
173
  group?: any;
170
174
  }): Promise<{}>;
175
+ upsertBySlugField(fields: Array<any>, index: string, { ref, req, parent_slug, input, tags, group }?: {
176
+ ref?: string;
177
+ req?: Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
178
+ parent_slug?: string;
179
+ input?: {};
180
+ tags?: TagFile;
181
+ group?: any;
182
+ }): Promise<{}>;
171
183
  findStream(slug: string, namespace: string, { result, lang_code, field_exclude, multiple, relationship, file, image, is_lang, stream, use_param }?: {
172
184
  result?: any[];
173
185
  lang_code?: string;
@@ -295,7 +307,7 @@ export declare class StreamUtil {
295
307
  stripUnknown?: boolean;
296
308
  builder?: boolean;
297
309
  }): Promise<Joi.ObjectSchema<any>>;
298
- validate(slug: string, namespace: string, input: any, { req, isNew, default_value, lang, stripUnknown, inputLang, inputLangSeparate, prefixMessage, builder, field_exclude }?: {
310
+ validate(slug: string, namespace: string, input: any, { req, isNew, default_value, lang, stripUnknown, inputLang, inputLangSeparate, prefixMessage, builder, field_option, field_exclude }?: {
299
311
  req?: Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
300
312
  isNew?: boolean;
301
313
  default_value?: {};
@@ -305,6 +317,7 @@ export declare class StreamUtil {
305
317
  inputLangSeparate?: boolean;
306
318
  prefixMessage?: string;
307
319
  builder?: boolean;
320
+ field_option?: {};
308
321
  field_exclude?: any[];
309
322
  }): Promise<any>;
310
323
  validateByField(streams: Array<any>, input: any, { req, isNew, default_value, lang, stripUnknown, inputLang, inputLangSeparate, prefixMessage }?: {