Newer
Older
Marin Karamihalev
committed
import {
CommandType,
DecodeOptions,
GetNestedReturn,
UspProperty,
UspPropertyList,
} from "../types";
const digitRe = /^\d+$/;
export const isDigit = (v: any) => digitRe.test(v);
const firstIsIndex = (s: string) => digitDotRe.test(s);
// based on https://stackoverflow.com/questions/54733539/javascript-implementation-of-lodash-set-method
const set = (obj, path, value) => {
if (Object(obj) !== obj) return obj;
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
path
.slice(0, -1)
.reduce(
(a, c, i) =>
Object(a[c]) === a[c]
? a[c]
: (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {}),
obj
)[path[path.length - 1]] = value;
return obj;
};
// Based on: https://www.30secondsofcode.org/js/s/unflatten-object
export const unflatten = (obj: any) =>
Object.keys(obj).reduce(
(res, k) => {
k.split(".")
.map((v) => (isDigit(v) ? parseInt(v) - 1 : v))
.reduce(
(acc: any, e, i, keys) =>
acc[e] ||
(acc[e] = isNaN(Number(keys[i + 1]))
? keys.length - 1 === i
? obj[k]
: {}
: []),
res
);
return res;
},
firstIsIndex(Object.keys(obj)[0]) ? [] : {}
);
export const search = (obj: any, key: string): any => {
if (typeof obj !== "object") return null;
if (obj[key]) return obj[key];
for (const val of Object.values(obj)) {
const s = search(val, key);
if (s) return s;
}
};
export const searchParent = (
obj: any,
key: string
): Record<string, any> | undefined => {
if (typeof obj !== "object") return;
if (obj[key]) return obj;
for (const val of Object.values(obj)) {
const s = searchParent(val, key);
if (s) return s;
}
};
const fixPath = (s: string): string =>
s
.split(".")
.filter((it) => it !== "")
.map((it) => (isDigit(it) ? `[${parseInt(it) - 1}]` : it))
.join(".")
.split(".[")
.join("[");
Marin Karamihalev
committed
export const convertToNestedObject = (arr: any[]) => {
.map((it) =>
Object.entries(it.resultParams).map(([key, value]) => ({
path: fixPath(it.resolvedPath + key),
value,
}))
)
.flat(1)
.sort((a, b) => a.path.localeCompare(b.path))
.forEach(({ path, value }) => {
set(res, path, value);
});
return res;
};
export const hasMultipleIndexes = (
arr: string[],
pathSplit: string[]
): boolean =>
arr.some((it) => {
const spl = it.split(".");
return spl.length > pathSplit.length && isDigit(spl[pathSplit.length - 1]);
});
const _searchAll = (obj: any, key: string): any[] =>
typeof obj !== "object"
? []
: Object.entries(obj).reduce(
(acc, [k, v]) => [...acc, k === key ? v : _searchAll(v, key)],
[] as any[]
);
export const searchAll = (obj: any, key: string) =>
_searchAll(obj, key).flat(Infinity);
export const extractCommand = (msg: {
[key: string]: any;
}): CommandType | undefined => {
const msgType: string | undefined = search(msg, "msgType");
if (!msgType) {
const id: string | undefined = search(msg, "msgId");
const [frst] = id ? id.split("@") : [""];
return frst.toUpperCase().replace("_RESP", "") as CommandType;
return msgType.replace("_RESP", "") as CommandType;
export const unwrapObject = (data: any): any =>
!Array.isArray(data) &&
typeof data === "object" &&
Object.keys(data).length === 1
? Object.values(data)[0]
: data;
export const unwrapArray = (arr: any) =>
Array.isArray(arr) && arr.length === 1 ? arr[0] : arr;
export const isEmptyObject = (obj: any): boolean =>
obj !== null &&
obj !== undefined &&
obj &&
typeof obj === "object" &&
Object.keys(obj).length === 0;
Marin Karamihalev
committed
export const isEmpty = (v: any): boolean => isEmptyObject(v);
export function makeBuffer(
payload: any,
options: Record<string, string>
) {
const NoSessionContextRecord = rootRecord.lookupType(
"usp_record.NoSessionContextRecord"
);
const noSessionContextRecordMsg = NoSessionContextRecord.create({
payload,
});
const record: any = rootRecord.lookupType("usp_record.Record");
const recordMsg = record.create({
version: "1.0",
PayloadSecurity: record.PayloadSecurity.PLAINTEXT,
noSessionContext: noSessionContextRecordMsg,
...options,
});
const buffer = record.encode(recordMsg).finish();
return buffer;
}
export const uniq = (initial?: string): string =>
(initial || "") +
(
Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
).toUpperCase();
export const parseID = (msg: any) => {
const foundId = search(msg, "msgId");
// if id is formatted by me (command@) then use, otherwise check for sub id
const id = foundId.includes("@")
? foundId
: search(msg, "subscriptionId") || null;
return id;
};
Marin Karamihalev
committed
const grab = (item: any, key: string) =>
Array.isArray(item)
? item.find((val) => val !== null && val !== undefined)
: item[key];
const skipKeys = (obj: any, keys: string[]) =>
keys.length === 1
? grab(obj, keys[0])
: skipKeys(grab(obj, keys[0]), keys.slice(1));
Marin Karamihalev
committed
const removeNulls = (obj: any) =>
typeof obj !== "object"
? obj
: Array.isArray(obj)
? obj.filter((v) => v !== null).map(removeNulls)
: Object.entries(obj).reduce(
(acc, [key, value]) => ({
[key]: Array.isArray(value)
? value.filter((v) => v !== null).map(removeNulls)
: removeNulls(value),
...acc,
}),
{}
);
Marin Karamihalev
committed
const pathJoin = (a: string, b: string) =>
a.endsWith(".") ? a + b : a + "." + b;
Marin Karamihalev
committed
const addQueries = (obj: any, path: string) =>
typeof obj !== "object"
? obj
: Array.isArray(obj)
? obj
.map((v, i) =>
v === null
? null
: addQueries(v, pathJoin(path, (i + 1).toString()) + ".")
)
.filter((v) => v !== null)
: {
__query__: path,
...Object.entries(obj).reduce(
(acc, [key, val]) => ({
...acc,
[key]:
typeof val !== "object"
? val
: addQueries(val, pathJoin(path, key) + "."),
}),
{}
),
};
Marin Karamihalev
committed
reqPathResults: PathResult[],
decodeOptions?: DecodeOptions
) => {
const retainPath = decodeOptions?.retainPath === true;
Marin Karamihalev
committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
const results = reqPathResults.map((resolvedResult) => {
const respType = determineResponseType(resolvedResult);
if (resolvedResult.resolvedPathResults === undefined) return null;
const results = resolvedResult.resolvedPathResults || [];
if (respType === ResponseType.Property) {
const result = Object.values(results[0].resultParams)[0];
return !retainPath
? result
: ({ __query__: resolvedResult.requestedPath, result } as UspProperty);
}
if (respType === ResponseType.PropertyList) {
const result = results.map(
(result) => Object.values(result.resultParams)[0]
);
return !retainPath
? result
: ({
__query__: resolvedResult.requestedPath,
result: result.map((str, i) => ({
__query__:
results[i].resolvedPath +
Object.keys(results[i].resultParams)[0],
result: str,
})),
} as UspPropertyList);
}
if (
respType === ResponseType.Object ||
respType === ResponseType.ObjectList
) {
const mainObject = skipKeys(
convertToNestedObject(results),
resolvedResult.requestedPath.split(".").slice(0, -1)
);
const cleanedObject = removeNulls(mainObject);
return !retainPath
? cleanedObject
: {
__query__: resolvedResult.requestedPath,
result: addQueries(mainObject, resolvedResult.requestedPath),
};
}
return null;
});
return results.length === 1 ? results[0] : results;
};
export type PathResult = {
requestedPath: string;
resolvedPathResults?: {
resolvedPath: string;
resultParams: {
key: string;
};
}[];
};
export enum ResponseType {
Property = "Property",
PropertyList = "PropertyList",
Object = "Object",
ObjectList = "ObjectList",
}
const containsQuery = (path: string): boolean =>
path.split(".").some((part) => part.includes("*") || part.includes("["));
const endsWithProperty = (path: string): boolean =>
/^.+\.[A-Za-z]+$/.test(path);
const endsWithIndex = (path: string): boolean => /^.+\.\d+\.$/.test(path);
const endsWithIndexedProperty = (path: string): boolean =>
/^.+\.\d+\..+$/.test(path.split(".").slice(-2)[0]);
const containsIndexes = (pathResult: PathResult): boolean =>
pathResult.resolvedPathResults === undefined
? false
: pathResult.resolvedPathResults.some(
({ resolvedPath, resultParams }) =>
(endsWithIndex(resolvedPath) &&
resolvedPath.split(".").length ===
pathResult.requestedPath.split(".").length + 1) ||
Object.keys(resultParams).some((key) =>
endsWithIndexedProperty(pathResult.requestedPath + key)
)
);
const determineResponseType = (pathResult: PathResult): ResponseType => {
const isQuery = containsQuery(pathResult.requestedPath);
if (endsWithProperty(pathResult.requestedPath))
return isQuery ? ResponseType.PropertyList : ResponseType.Property;
if (isQuery || containsIndexes(pathResult)) return ResponseType.ObjectList;
if (endsWithIndex(pathResult.requestedPath)) return ResponseType.Object;
return ResponseType.Object;