2016-11-10 05:56:23 +00:00
|
|
|
import * as db from '../common/database';
|
2016-11-27 21:42:38 +00:00
|
|
|
import {MAX_RESPONSES} from '../common/constants';
|
2016-09-21 20:32:45 +00:00
|
|
|
|
2016-11-22 19:42:10 +00:00
|
|
|
export const name = 'Response';
|
2016-10-02 20:57:00 +00:00
|
|
|
export const type = 'Response';
|
|
|
|
export const prefix = 'res';
|
2016-11-22 19:42:10 +00:00
|
|
|
|
2016-10-02 20:57:00 +00:00
|
|
|
export function init () {
|
2016-11-10 01:15:27 +00:00
|
|
|
return {
|
2016-10-02 20:57:00 +00:00
|
|
|
statusCode: 0,
|
|
|
|
statusMessage: '',
|
2016-10-27 16:45:44 +00:00
|
|
|
contentType: '',
|
2016-10-02 20:57:00 +00:00
|
|
|
url: '',
|
|
|
|
bytesRead: 0,
|
|
|
|
elapsedTime: 0,
|
|
|
|
headers: [],
|
|
|
|
cookies: [],
|
|
|
|
body: '',
|
2016-10-26 23:22:15 +00:00
|
|
|
encoding: 'utf8', // Legacy format
|
2016-10-02 20:57:00 +00:00
|
|
|
error: ''
|
2017-03-03 20:09:08 +00:00
|
|
|
};
|
2016-10-02 20:57:00 +00:00
|
|
|
}
|
2016-09-21 20:32:45 +00:00
|
|
|
|
2016-11-22 19:42:10 +00:00
|
|
|
export function migrate (doc) {
|
|
|
|
return doc;
|
|
|
|
}
|
|
|
|
|
2016-11-27 21:42:38 +00:00
|
|
|
export function getById (id) {
|
|
|
|
return db.get(type, id);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function all () {
|
|
|
|
return db.all(type);
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function removeForRequest (parentId) {
|
|
|
|
db.removeBulkSilently(type, {parentId});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function findRecentForRequest (requestId, limit) {
|
|
|
|
return db.findMostRecentlyModified(type, {parentId: requestId}, limit);
|
|
|
|
}
|
|
|
|
|
2017-02-20 18:32:27 +00:00
|
|
|
export async function getLatestForRequest (requestId) {
|
|
|
|
const responses = await findRecentForRequest(requestId, 1);
|
|
|
|
return responses[0] || null;
|
|
|
|
}
|
|
|
|
|
2016-11-27 21:42:38 +00:00
|
|
|
export async function create (patch = {}) {
|
2016-09-21 20:32:45 +00:00
|
|
|
if (!patch.parentId) {
|
|
|
|
throw new Error('New Response missing `parentId`');
|
|
|
|
}
|
|
|
|
|
2016-11-27 21:42:38 +00:00
|
|
|
const {parentId} = patch;
|
|
|
|
|
|
|
|
// Delete all other responses before creating the new one
|
|
|
|
const allResponses = await db.findMostRecentlyModified(type, {parentId}, MAX_RESPONSES);
|
|
|
|
const recentIds = allResponses.map(r => r._id);
|
|
|
|
await db.removeBulkSilently(type, {parentId, _id: {$nin: recentIds}});
|
|
|
|
|
|
|
|
// Actually create the new response
|
2016-10-02 20:57:00 +00:00
|
|
|
return db.docCreate(type, patch);
|
|
|
|
}
|
2016-09-21 20:32:45 +00:00
|
|
|
|
2016-10-02 20:57:00 +00:00
|
|
|
export function getLatestByParentId (parentId) {
|
|
|
|
return db.getMostRecentlyModified(type, {parentId});
|
|
|
|
}
|