Created
May 18, 2017 13:05
-
-
Save VitorLuizC/5629874e4c24005e5144fe8954a86b8a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const levelup = require('levelup') | |
| const { NotFoundError } = require('level-errors') | |
| const database = levelup('./app/database', { createIfMissing: true }) | |
| /** | |
| * Opções do repositório. | |
| * @typedef RepositoryOptions | |
| * @type {Object} | |
| * @property {*} initialValue | |
| */ | |
| /** | |
| * Obtém os dados do repositório. | |
| * @returns {Promise.<*>} | |
| */ | |
| function pull() { | |
| return new Promise((resolve, reject) => { | |
| database.get(this.name, (err, data) => { | |
| if (err && !(err instanceof NotFoundError)) | |
| reject(err) | |
| resolve(JSON.parse(data) || this.options.initialValue) | |
| }) | |
| }) | |
| } | |
| /** | |
| * Envia dados ao repositório. | |
| * @param {*} data | |
| * @returns {Promise.<*>} | |
| */ | |
| function push(data) { | |
| return new Promise((resolve, reject) => { | |
| database.put(this.name, JSON.stringify(data), err => { | |
| if (err) | |
| reject(err) | |
| resolve(data) | |
| }) | |
| }) | |
| } | |
| /** | |
| * Obtém, pelo nome, a API do repositório. | |
| * @param {String} name | |
| * @param {RepositoryOptions} options | |
| */ | |
| function repository(name, options) { | |
| /** | |
| * Opções padrão do repositório. | |
| * @type {RepositoryOptions} | |
| */ | |
| const defaultOptions = { | |
| initialValue: null | |
| } | |
| options = Object.assign({}, defaultOptions, options) | |
| return { | |
| pull: pull.bind({ name, options }), | |
| push: push.bind({ name, options }) | |
| } | |
| } | |
| module.exports = repository |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment