UNPKG

9.33 kBJavaScriptView Raw
1// Copyright IBM Corp. 2014,2019. All Rights Reserved.
2// Node module: loopback-connector
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6'use strict';
7const SG = require('strong-globalize');
8const g = SG();
9const debug = require('debug')('loopback:connector');
10
11module.exports = Connector;
12
13/**
14 * Base class for LoopBack connector. This is more a collection of useful
15 * methods for connectors than a super class
16 * @class
17 */
18function Connector(name, settings) {
19 this._models = {};
20 this.name = name;
21 this.settings = settings || {};
22}
23
24/**
25 * @private
26 * Set the relational property to indicate the backend is a relational DB
27 * @type {boolean}
28 */
29Connector.prototype.relational = false;
30
31/**
32 * Check if the connector is for a relational DB
33 * @returns {Boolean} true for relational DB
34 */
35Connector.prototype.isRelational = function() {
36 return this.isRelational ||
37 (this.getTypes().indexOf('rdbms') !== -1);
38};
39
40/**
41 * Get types associated with the connector
42 * @returns {String[]} The types for the connector
43 */
44Connector.prototype.getTypes = function() {
45 return ['db', 'nosql'];
46};
47
48/**
49 * Get the default data type for ID
50 * @param {Object} prop Property definition
51 * @returns {Function} The default type for ID
52 */
53Connector.prototype.getDefaultIdType = function(prop) {
54 /* jshint unused:false */
55 return String;
56};
57
58/**
59 * Generate random id. Each data source model must override this method.
60 * @param {String} modelName Model name
61 * @returns {*} Data type varies from model to model,
62 */
63
64Connector.prototype.generateUniqueId = function(modelName) {
65 const idType = this.getDefaultIdType && this.getDefaultIdType();
66 const isTypeFunction = (typeof idType === 'function');
67 const id = this.generateValueByColumnType ? this.generateValueByColumnType(idType) :
68 (typeof idType === 'function' ? idType() : null);
69 return id;
70};
71
72/**
73 * Get the metadata for the connector
74 * @returns {Object} The metadata object
75 * @property {String} type The type for the backend
76 * @property {Function} defaultIdType The default id type
77 * @property {Boolean} [isRelational] If the connector represents a relational
78 * database
79 * @property {Object} schemaForSettings The schema for settings object
80 */
81Connector.prototype.getMetadata = function() {
82 if (!this._metadata) {
83 this._metadata = {
84 types: this.getTypes(),
85 defaultIdType: this.getDefaultIdType(),
86 isRelational: this.isRelational(),
87 schemaForSettings: {},
88 };
89 }
90 return this._metadata;
91};
92
93/**
94 * Execute a command with given parameters
95 * @param {String|Object} command The command such as SQL
96 * @param {Array} [params] An array of parameter values
97 * @param {Object} [options] Options object
98 * @param {Function} [callback] The callback function
99 */
100Connector.prototype.execute = function(command, params, options, callback) {
101 throw new Error(g.f('execute() must be implemented by the connector'));
102};
103
104/**
105 * Get the model definition by name
106 * @param {String} modelName The model name
107 * @returns {ModelDefinition} The model definition
108 */
109Connector.prototype.getModelDefinition = function(modelName) {
110 return this._models[modelName];
111};
112
113/**
114 * Get connector specific settings for a given model, for example,
115 * ```
116 * {
117 * "postgresql": {
118 * "schema": "xyz"
119 * }
120 * }
121 * ```
122 *
123 * @param {String} modelName Model name
124 * @returns {Object} The connector specific settings
125 */
126Connector.prototype.getConnectorSpecificSettings = function(modelName) {
127 const settings = this.getModelDefinition(modelName).settings || {};
128 return settings[this.name];
129};
130
131/**
132 * Get model property definition
133 * @param {String} modelName Model name
134 * @param {String} propName Property name
135 * @returns {Object} Property definition
136 */
137Connector.prototype.getPropertyDefinition = function(modelName, propName) {
138 const model = this.getModelDefinition(modelName);
139 return Connector.getNestedPropertyDefinition(
140 model.model.definition,
141 propName.split('.'),
142 );
143};
144
145/**
146 * Helper function to get nested property definition
147 * @param {Object} definition Model name
148 * @param {Array} propPath
149 * @returns {Object} Property definition
150 */
151Connector.getNestedPropertyDefinition = function(definition, propPath) {
152 const properties = definition.properties || {};
153 const prop = properties[propPath[0]];
154 const isPropUndefined = typeof prop === 'undefined';
155 const isArray = !isPropUndefined && Array.isArray(prop.type);
156 const isFunction = !isPropUndefined && !isArray && typeof prop.type === 'function';
157
158 if (propPath.length === 1) return prop;
159
160 if (isPropUndefined || (propPath.length > 1 && (isArray && prop.type.length === 0))) {
161 return undefined;
162 }
163
164 const nextDefinition =
165 (isArray && prop.type[0].definition) ||
166 (isFunction && prop.type.definition);
167
168 if (nextDefinition === undefined) {
169 return undefined;
170 } else {
171 return Connector.getNestedPropertyDefinition(
172 nextDefinition,
173 propPath.slice(1),
174 );
175 }
176};
177
178/**
179 * Look up the data source by model name
180 * @param {String} model The model name
181 * @returns {DataSource} The data source
182 */
183Connector.prototype.getDataSource = function(model) {
184 const m = this.getModelDefinition(model);
185 if (!m) {
186 debug('Model not found: ' + model);
187 }
188 return m && m.model.dataSource;
189};
190
191/**
192 * Get the id property name
193 * @param {String} model The model name
194 * @returns {String} The id property name
195 */
196Connector.prototype.idName = function(model) {
197 return this.getDataSource(model).idName(model);
198};
199
200/**
201 * Get the id property names
202 * @param {String} model The model name
203 * @returns {String[]} The id property names
204 */
205Connector.prototype.idNames = function(model) {
206 return this.getDataSource(model).idNames(model);
207};
208
209/**
210 * Get the id index (sequence number, starting from 1)
211 * @param {String} model The model name
212 * @param {String} prop The property name
213 * @returns {Number} The id index, undefined if the property is not part
214 * of the primary key
215 */
216Connector.prototype.id = function(model, prop) {
217 const p = this.getModelDefinition(model).properties[prop];
218 return p && p.id;
219};
220
221/**
222 * Hook to be called by DataSource for defining a model
223 * @param {Object} modelDefinition The model definition
224 */
225Connector.prototype.define = function(modelDefinition) {
226 modelDefinition.settings = modelDefinition.settings || {};
227 this._models[modelDefinition.model.modelName] = modelDefinition;
228};
229
230/**
231 * Hook to be called by DataSource for defining a model property
232 * @param {String} model The model name
233 * @param {String} propertyName The property name
234 * @param {Object} propertyDefinition The object for property definition
235 */
236Connector.prototype.defineProperty = function(model, propertyName, propertyDefinition) {
237 const modelDef = this.getModelDefinition(model);
238 modelDef.properties[propertyName] = propertyDefinition;
239};
240
241/**
242 * Disconnect from the connector
243 * @param {Function} [cb] Callback function
244 */
245Connector.prototype.disconnect = function disconnect(cb) {
246 // NO-OP
247 if (cb) {
248 process.nextTick(cb);
249 }
250};
251
252/**
253 * Get the id value for the given model
254 * @param {String} model The model name
255 * @param {Object} data The model instance data
256 * @returns {*} The id value
257 *
258 */
259Connector.prototype.getIdValue = function(model, data) {
260 return data && data[this.idName(model)];
261};
262
263/**
264 * Set the id value for the given model
265 * @param {String} model The model name
266 * @param {Object} data The model instance data
267 * @param {*} value The id value
268 *
269 */
270Connector.prototype.setIdValue = function(model, data, value) {
271 if (data) {
272 data[this.idName(model)] = value;
273 }
274};
275
276/**
277 * Test if a property is nullable
278 * @param {Object} prop The property definition
279 * @returns {boolean} true if nullable
280 */
281Connector.prototype.isNullable = function(prop) {
282 if (prop.required || prop.id) {
283 return false;
284 }
285 if (prop.nullable || prop['null'] || prop.allowNull) {
286 return true;
287 }
288 if (prop.nullable === false || prop['null'] === false ||
289 prop.allowNull === false) {
290 return false;
291 }
292 return true;
293};
294
295/**
296 * Return the DataAccessObject interface implemented by the connector
297 * @returns {Object} An object containing all methods implemented by the
298 * connector that can be mixed into the model class. It should be considered as
299 * the interface.
300 */
301Connector.prototype.getDataAccessObject = function() {
302 return this.DataAccessObject;
303};
304
305/*!
306 * Define aliases to a prototype method/property
307 * @param {Function} cls The class that owns the method/property
308 * @param {String} methodOrPropertyName The official property method/property name
309 * @param {String|String[]} aliases Aliases to the official property/method
310 */
311Connector.defineAliases = function(cls, methodOrPropertyName, aliases) {
312 if (typeof aliases === 'string') {
313 aliases = [aliases];
314 }
315 if (Array.isArray(aliases)) {
316 aliases.forEach(function(alias) {
317 if (typeof alias === 'string') {
318 Object.defineProperty(cls, alias, {
319 get: function() {
320 return this[methodOrPropertyName];
321 },
322 });
323 }
324 });
325 }
326};
327
328/**
329 * `command()` and `query()` are aliases to `execute()`
330 */
331Connector.defineAliases(Connector.prototype, 'execute', ['command', 'query']);