UNPKG

@coolgk/utils

Version:

javascript, typescript utility and wrapper functions and classes: array, string, base64, ampq, bcrypt, cache, captcha, csv, email, jwt, number, pdf, tmp, token, unit conversion, url params, session, form data, google sign in, facebook sign in

51 lines (49 loc) 1.6 kB
/*! * @package @coolgk/utils * @version 3.1.4 * @link https://github.com/coolgk/node-utils * @license MIT * @author Daniel Gong <daniel.k.gong@gmail.com> * * Copyright (c) 2017 Daniel Gong <daniel.k.gong@gmail.com>. All rights reserved. * Licensed under the MIT License. */ "use strict"; /*! * Copyright (c) 2017 Daniel Gong <daniel.k.gong@gmail.com>. All rights reserved. * Licensed under the MIT License. */ Object.defineProperty(exports, "__esModule", { value: true }); class Cache { constructor(options) { this._redisClient = options.redisClient; } set(name, value, expiry = 0) { const stringValue = JSON.stringify(value); return expiry ? this.command('setex', name, expiry, stringValue) : this.command('set', name, stringValue); } get(name) { return this.command('get', name).then((value) => JSON.parse(value)); } delete(name) { return this.command('del', name); } getSetIfNull(name, callback, expiry = 0) { return this.get(name).then((cachedValue) => { if (null === cachedValue) { return Promise.resolve(callback()).then((value) => this.set(name, value, expiry).then(() => value)); } return cachedValue; }); } command(command, ...params) { return new Promise((resolve, reject) => { params.push((error, response) => { error ? reject(error) : resolve(response); }); this._redisClient[command](...params); }); } } exports.Cache = Cache; exports.default = Cache;