UNPKG

3.05 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2018, Kinvey, Inc. All rights reserved.
3 *
4 * This software is licensed to you under the Kinvey terms of service located at
5 * http://www.kinvey.com/terms-of-use. By downloading, accessing and/or using this
6 * software, you hereby accept such terms of service (and any agreement referenced
7 * therein) and agree that you have read, understand and agree to be bound by such
8 * terms of service and are of legal age to agree to such terms with Kinvey.
9 *
10 * This software contains valuable confidential and proprietary information of
11 * KINVEY, INC and is subject to applicable licensing agreements.
12 * Unauthorized reproduction, transmission or distribution of this file and its
13 * contents is a violation of applicable laws.
14 */
15
16const async = require('async');
17
18const { Errors } = require('./Constants');
19const KinveyError = require('./KinveyError');
20const { isEmpty, isEnvID, isUUID } = require('./Utils');
21
22class 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 // it looks like an id, so let's try that first
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 // handles the case where identifier looks like an id but is a name, actually - the name could be an UUID
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
106module.exports = BaseService;