UNPKG

@canonical/jujulib

Version:
60 lines (58 loc) 2.07 kB
// Copyright 2020 Canonical Ltd. // Licensed under the LGPLv3, see LICENSE.txt file for details. export var Label; (function (Label) { Label["UNKNOWN_ERROR"] = "Unknown error"; })(Label || (Label = {})); /** Automatically bind all methods of the given object to the object itself. @param obj The object whose method must be bound. */ export function autoBind(obj) { const names = Object.getOwnPropertyNames(obj.constructor.prototype); for (let i = 0; i < names.length; i++) { const name = names[i]; if (name !== "constructor" && typeof obj[name] === "function") { obj[name] = obj[name].bind(obj); } } } /** Create an async handler which will either return a value to a supplied callback, or call the appropriate method on the promise resolve/reject. @param [callback] The optional callback. @param [resolve] The optional promise resolve function. @param [reject] The optional promise reject function. @param [transform] The optional response transform function. @return The returned function takes two arguments (err, value). If the the callback is a function the two arguments will be passed through to the callback in the same order. If no callback is supplied, the promise resolve or reject method will be called depending on the existence of an error value. */ export function createAsyncHandler(callback, resolve, reject, transform) { return { resolve: (value) => { if (transform) { value = transform(value); } callback ? callback(null, value) : resolve(value); }, reject: callback ? callback : reject, }; } /** Convert given input to an Error object. @param error - The input to be converted to an Error object. @returns An Error object. */ export function toError(error) { if (error instanceof Error) { return error; } if (typeof error === "string") { return new Error(error); } return new Error(Label.UNKNOWN_ERROR); } //# sourceMappingURL=utils.js.map