insomnia/app/database/index.js
2016-04-17 13:35:35 -07:00

126 lines
2.3 KiB
JavaScript

import PouchDB from 'pouchdb';
import * as methods from '../constants/global';
import {generateId} from './util'
let db = new PouchDB('insomnia.db');
// For browser console debugging
// global.db = db;
export let changes = db.changes({
since: 'now',
live: true,
include_docs: true,
return_docs: false
}).on('complete', function (info) {
console.log('complete', info);
}).on('error', function (err) {
console.log('error', err);
});
export function allDocs () {
return db.allDocs({include_docs: true});
}
export function get (id) {
return db.get(id);
}
export function update (doc, patch = {}) {
const updatedDoc = Object.assign(
{},
doc,
patch,
{modified: Date.now()}
);
return db.put(updatedDoc).catch(e => {
if (e.status === 409) {
console.warn('Retrying document update for', updatedDoc);
get(doc._id).then(dbDoc => {
update(dbDoc, patch);
});
}
});
}
export function remove (doc) {
return update(doc, {_deleted: true});
}
// ~~~~~~~~~~~~~~~~~~~ //
// DEFAULT MODEL STUFF //
// ~~~~~~~~~~~~~~~~~~~ //
function modelCreate (idPrefix, defaults, patch = {}) {
const model = Object.assign(
defaults,
patch,
// Required Generated Fields
{
_id: generateId(idPrefix),
_rev: undefined,
type: 'Request',
created: Date.now(),
modified: Date.now()
}
);
update(model);
return model;
}
// ~~~~~~~ //
// REQUEST //
// ~~~~~~~ //
export function requestCreate (patch = {}) {
return modelCreate('req', {
url: '',
name: 'New Request',
method: methods.METHOD_GET,
body: '',
params: [],
contentType: 'text/plain',
headers: [],
authentication: {},
parent: null
}, patch);
}
export function requestCopy (originalRequest) {
const name = `${originalRequest.name} (Copy)`;
return requestCreate(Object.assign({}, originalRequest, {name}));
}
// ~~~~~~~~~~~~~ //
// REQUEST GROUP //
// ~~~~~~~~~~~~~ //
export function requestGroupCreate (patch = {}) {
return modelCreate('grp', {
collapsed: false,
name: 'New Request Group',
environment: {},
parent: null
}, patch);
}
// ~~~~~~~~~//
// RESPONSE //
// ~~~~~~~~~//
export function responseCreate (patch = {}) {
return modelCreate('grp', {
collapsed: false,
name: 'New Request Group',
environment: {},
parent: null
}, patch);
}