1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | const async = require('async');
|
17 |
|
18 | const { Errors } = require('./Constants');
|
19 | const KinveyError = require('./KinveyError');
|
20 | const { isEmpty, isEnvID, isUUID } = require('./Utils');
|
21 |
|
22 | class BaseService {
|
23 | constructor(cliManager) {
|
24 | this.cliManager = cliManager;
|
25 | }
|
26 |
|
27 | getAllEntities(endpoint, done) {
|
28 | this.cliManager.sendRequest({ endpoint }, done);
|
29 | }
|
30 |
|
31 | getEntityByName(endpoint, name, done) {
|
32 | this.getAllEntities(endpoint, (err, data) => {
|
33 | if (err) {
|
34 | return done(err);
|
35 | }
|
36 |
|
37 | const entities = data.filter(x => x.name === name);
|
38 | if (isEmpty(entities)) {
|
39 | return done(new KinveyError(Errors.NoEntityFound));
|
40 | }
|
41 |
|
42 | if (entities.length > 1) {
|
43 | return done(new KinveyError(Errors.TooManyEntitiesFound));
|
44 | }
|
45 |
|
46 | done(null, entities[0]);
|
47 | });
|
48 | }
|
49 |
|
50 | getEntityByIdOrName(identifier, endpointAll, endpointId, done) {
|
51 | const couldBeId = isUUID(identifier) || isEnvID(identifier);
|
52 | let entity;
|
53 |
|
54 | async.series([
|
55 | (next) => {
|
56 |
|
57 | if (couldBeId) {
|
58 | this.cliManager.sendRequest({ endpoint: endpointId }, (err, data) => {
|
59 | if (err) {
|
60 | if (err.name.includes('NotFound')) {
|
61 | return next(null);
|
62 | }
|
63 |
|
64 | return next(err);
|
65 | }
|
66 |
|
67 | entity = data;
|
68 | next();
|
69 | });
|
70 | } else {
|
71 | this.getEntityByName(endpointAll, identifier, (err, data) => {
|
72 | if (err) {
|
73 | return next(err);
|
74 | }
|
75 |
|
76 | entity = data;
|
77 | next();
|
78 | });
|
79 | }
|
80 | },
|
81 | (next) => {
|
82 | if (!isEmpty(entity)) {
|
83 | return setImmediate(next);
|
84 | }
|
85 |
|
86 |
|
87 | this.getEntityByName(endpointAll, identifier, (err, data) => {
|
88 | if (err) {
|
89 | return next(err);
|
90 | }
|
91 |
|
92 | entity = data;
|
93 | next();
|
94 | });
|
95 | }
|
96 | ], (err) => {
|
97 | if (err) {
|
98 | return done(err);
|
99 | }
|
100 |
|
101 | done(null, entity);
|
102 | });
|
103 | }
|
104 | }
|
105 |
|
106 | module.exports = BaseService;
|