Skip to content

Instantly share code, notes, and snippets.

@AdamSaleh
Created September 13, 2017 11:37
Show Gist options
  • Save AdamSaleh/1bb6a3861715f7114e3a9451e84312b5 to your computer and use it in GitHub Desktop.
Save AdamSaleh/1bb6a3861715f7114e3a9451e84312b5 to your computer and use it in GitHub Desktop.
const PouchDB = require('pouchdb');
const db = new PouchDB('./database');
const express = require('express');
const app = express();
const router = express.Router();
app.use('/locker', router);
app.listen(8800, function () {
console.log('Listening at http://localhost:8800/locker');
});
router.get('/', (request, response) => {
response.status(200).json('Hello');
});
function wrap (responder) {
return async (req, res) => {
try {
await responder(req, res);
} catch (exception) {
res.status(500).json(exception);
}
};
}
router.post('/', wrap(async (req, res) => {
const dbResponse = await db.post({'_attachments': {}});
res.status(200).json(dbResponse);
}));
router.get('/:id/items', wrap(async (req, res) => {
const id = req.params.id;
const {_attachments} = await db.get(id);
res.status(200).json(Object.keys(_attachments));
}));
router.delete('/:id', wrap(async ({params: {id}}, res) => {
const doc = await db.get(id);
const dbResponse = await db.remove(id, doc._rev);
res.json(dbResponse);
}));
function getReqBuffer (req) {
return new Promise((resolve, reject) => {
const bufs = [];
req.on('data', d => bufs.push(d));
req.on('end', () => resolve(Buffer.concat(bufs)));
req.on('err', e => reject(e));
});
}
router.post('/:id/item/:name', wrap(async (req, res) => {
const id = req.params.id;
const name = req.params.name;
const buffer = await getReqBuffer(req);
const doc = await db.get(id);
doc['_attachments'][name] = {
'content_type': 'application/octet-stream',
'data': buffer
};
const response = await db.put(doc);
res.json(response);
}));
router.get('/:id/item/:name', wrap(async (req, res) => {
const id = req.params.id;
const name = req.params.name;
const response = await db.getAttachment(id, name);
res.type('application/octet-stream');
res.end(response, 'binary');
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment