import type { Request } from 'insomnia-data'; import { database as db, models } from 'insomnia-data'; const { type, name } = models.request; export function create(patch: Partial = {}) { if (!patch.parentId) { throw new Error(`New Requests missing \`parentId\`: ${JSON.stringify(patch)}`); } return db.docCreate(type, patch); } export function getById(id: string): Promise { return db.findOne(type, { _id: id }); } export function getByParentId(parentId: string) { return db.findOne(type, { parentId: parentId }); } export function findByParentId(parentId: string) { return db.find(type, { parentId: parentId }); } export function update(request: Request, patch: Partial) { return db.docUpdate(request, patch); } export async function duplicate(request: Request, patch: Partial = {}) { // Only set name and "(Copy)" if the patch does // not define it and the request itself has a name. // Otherwise leave it blank so the request URL can // fill it in automatically. if (!patch.name && request.name) { patch.name = `${request.name} (Copy)`; } // Get sort key of next request const q = { metaSortKey: { $gt: request.metaSortKey, }, }; const [nextRequest] = await db.find(type, q, { metaSortKey: 1, }); const nextSortKey = nextRequest ? nextRequest.metaSortKey : request.metaSortKey + 100; // Calculate new sort key const sortKeyIncrement = (nextSortKey - request.metaSortKey) / 2; const metaSortKey = request.metaSortKey + sortKeyIncrement; return db.duplicate(request, { name, metaSortKey, ...patch, }); } export function remove(request: Request) { return db.remove(request); } export async function all() { return db.find(type); }