1 | // Copyright IBM Corp. 2016,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 | ;
|
7 |
|
8 | const createPromiseCallback = require('./utils').createPromiseCallback;
|
9 | const debug = require('debug')('loopback:connector:model-key-composer');
|
10 | const g = require('strong-globalize')();
|
11 |
|
12 | /**
|
13 | * Build a single key string from a tuple (modelName, key).
|
14 | *
|
15 | * This method is typically used by KeyValue connectors to build a single
|
16 | * key string for a given modelName+key tuple.
|
17 | *
|
18 | * @param {String} modelName
|
19 | * @param {String} key
|
20 | * @callback {Function} cb The callback to receive the composed value.
|
21 | * @param {Error} err
|
22 | * @param {String} composedKey
|
23 | * @promise
|
24 | */
|
25 | exports.compose = function composeKeyFromModelNameAndKey(modelName, key, cb) {
|
26 | cb = cb || createPromiseCallback();
|
27 |
|
28 | // Escape model name to prevent collision
|
29 | // 'model' + 'foo:bar' --vs-- 'model:foo' + 'bar'
|
30 | const value = encodeURIComponent(modelName) + ':' + key;
|
31 |
|
32 | setImmediate(function() {
|
33 | cb(null, value);
|
34 | });
|
35 | return cb.promise;
|
36 | };
|
37 |
|
38 | const PARSE_KEY_REGEX = /^([^:]*):(.*)/;
|
39 |
|
40 | /**
|
41 | * Parse a composed key string into a tuple (modelName, key).
|
42 | *
|
43 | * This method is typically used by KeyValue connectors to parse a composed
|
44 | * key string returned by SCAN/ITERATE method back to the expected
|
45 | * modelName+tuple key.
|
46 | *
|
47 | * @param {String} composed The composed key as returned by `composeKey`
|
48 | * @callback {Function} cb The callback to receive the parsed result.
|
49 | * @param {Error} err
|
50 | * @param {Object} result The result with properties `modelName` and `key`.
|
51 | * @promise
|
52 | */
|
53 | exports.parse = function(composed, cb) {
|
54 | cb = cb || createPromiseCallback();
|
55 |
|
56 | const matchResult = composed.match(PARSE_KEY_REGEX);
|
57 | if (matchResult) {
|
58 | const result = {
|
59 | modelName: matchResult[1],
|
60 | key: matchResult[2],
|
61 | };
|
62 | setImmediate(function() {
|
63 | cb(null, result);
|
64 | });
|
65 | } else {
|
66 | debug('Invalid key - missing model-name prefix: %s', composed);
|
67 | const err = new Error(g.f(
|
68 | 'Invalid key %j - missing model-name prefix',
|
69 | composed,
|
70 | ));
|
71 | err.code = 'NO_MODEL_PREFIX';
|
72 | setImmediate(function() {
|
73 | cb(err);
|
74 | });
|
75 | }
|
76 | return cb.promise;
|
77 | };
|