Normalize remove call wrapping to handle storagemaps

This commit is contained in:
Timothy Farrell 2018-06-24 21:46:43 -05:00
parent d05b929089
commit 1c5e4061f5

View File

@ -23,20 +23,13 @@ export function PouchDBAttachmentProxy({ save, getFn, remove }) {
if (att.type !== STORAGE_MIMETYPE) { if (att.type !== STORAGE_MIMETYPE) {
return att; return att;
} }
return await getFn.call(this, await readStorageMap(att)); return await getFn(await readStorageMap(att));
}; };
} }
if (remove) { if (remove) {
override.removeAttachment = async function removeAttachment(...args) { override.removeAttachment = async function removeAttachment(...args) {
const att = await pouchGetAttachment.apply(this, args); cleanupFiles(await pouchGetAttachment.apply(this, args));
if (att.type === STORAGE_MIMETYPE) {
try {
await remove.call(this, await readStorageMap(att));
} catch (e) {
error(`Failed to remove attachment ${args}`, e);
}
}
return await pouchRemoveAttachment.apply(this, args); return await pouchRemoveAttachment.apply(this, args);
}; };
} }
@ -51,12 +44,11 @@ export function PouchDBAttachmentProxy({ save, getFn, remove }) {
} }
// All documents must have a .name field. // All documents must have a .name field.
const deletedFiles = new Set(); const deletedFiles = [];
const attachments = []; const attachments = [];
docs.filter(d => d.$$type === 'file').forEach(f => { docs.filter(d => d.$$type === 'file').forEach(f => {
if (f._deleted) { if (f._deleted) {
const deleteArgs = [f._id, 'data', f._rev]; deletedFiles.push(pouchGetAttachment.call(this, f._id, 'data'));
deletedFiles.add(deleteArgs.concat(pouchGetAttachment.call(this, f._id, 'data')));
return; return;
} }
if (f._attachments && f._attachments.data.data instanceof Blob) { if (f._attachments && f._attachments.data.data instanceof Blob) {
@ -66,18 +58,17 @@ export function PouchDBAttachmentProxy({ save, getFn, remove }) {
} }
}); });
deletedFiles.forEach(cleanupFiles); Promise.all(deletedFiles).then(atts => atts.forEach(cleanupFiles));
return Promise.all( return Promise.all(
attachments.map(([doc, attName, blob]) => attachments.map(([doc, attName, blob]) =>
save save(blob)
.call(this, blob)
.then(resData => { .then(resData => {
deepAssign(doc, { deepAssign(doc, {
_attachments: { _attachments: {
[attName]: { [attName]: {
content_type: STORAGE_MIMETYPE, content_type: STORAGE_MIMETYPE,
data: btoa(JSON.stringify(resData.id)) data: btoa(JSON.stringify(resData))
} }
} }
}); });
@ -90,10 +81,13 @@ export function PouchDBAttachmentProxy({ save, getFn, remove }) {
}; };
} }
const cleanupFiles = backgroundTask( const cleanupFiles = backgroundTask(function(att) {
([id, attName, rev, attPromise]) => attPromise.then(att => remove(id, attName, rev, att)), if (att.type === STORAGE_MIMETYPE) {
false readStorageMap(att)
); .then(remove)
.catch(e => error(`Failed to remove attachment ${args}`, e));
}
}, false);
return override; return override;
} }