2019-02-03 15:36:08 +03:00
|
|
|
module.exports = (event, model) => {
|
|
|
|
const _ = require('lodash');
|
2020-08-11 20:44:21 +03:00
|
|
|
const {sequence} = require('@tryghost/promise');
|
2019-02-03 15:36:08 +03:00
|
|
|
const api = require('../../api');
|
|
|
|
|
2021-03-02 02:31:44 +03:00
|
|
|
const apiVersion = model.get('api_version') || 'v4';
|
2019-02-26 01:51:23 +03:00
|
|
|
|
|
|
|
const resourceName = event.match(/(\w+)\./)[1];
|
|
|
|
const docName = `${resourceName}s`;
|
2019-02-03 15:36:08 +03:00
|
|
|
|
|
|
|
const ops = [];
|
|
|
|
|
|
|
|
if (Object.keys(model.attributes).length) {
|
2019-02-26 01:35:52 +03:00
|
|
|
ops.push(() => {
|
|
|
|
let frame = {options: {previous: false, context: {user: true}}};
|
2019-02-03 15:36:08 +03:00
|
|
|
|
2019-02-26 01:35:52 +03:00
|
|
|
if (['posts', 'pages'].includes(docName)) {
|
|
|
|
frame.options.formats = ['mobiledoc', 'html', 'plaintext'];
|
|
|
|
frame.options.withRelated = ['tags', 'authors'];
|
|
|
|
}
|
2019-02-25 11:46:50 +03:00
|
|
|
|
2019-02-03 15:36:08 +03:00
|
|
|
return api.shared
|
|
|
|
.serializers
|
|
|
|
.handle
|
|
|
|
.output(model, {docName: docName, method: 'read'}, api[apiVersion].serializers.output, frame)
|
|
|
|
.then(() => {
|
|
|
|
return frame.response[docName][0];
|
|
|
|
});
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
ops.push(() => {
|
|
|
|
return Promise.resolve({});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Object.keys(model._previousAttributes).length) {
|
|
|
|
ops.push(() => {
|
|
|
|
const frame = {options: {previous: true, context: {user: true}}};
|
|
|
|
|
2019-02-26 01:35:52 +03:00
|
|
|
if (['posts', 'pages'].includes(docName)) {
|
|
|
|
frame.options.formats = ['mobiledoc', 'html', 'plaintext'];
|
|
|
|
frame.options.withRelated = ['tags', 'authors'];
|
|
|
|
}
|
|
|
|
|
2019-02-03 15:36:08 +03:00
|
|
|
return api.shared
|
|
|
|
.serializers
|
|
|
|
.handle
|
|
|
|
.output(model, {docName: docName, method: 'read'}, api[apiVersion].serializers.output, frame)
|
|
|
|
.then(() => {
|
|
|
|
return frame.response[docName][0];
|
|
|
|
});
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
ops.push(() => {
|
|
|
|
return Promise.resolve({});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-02-25 11:38:08 +03:00
|
|
|
return sequence(ops)
|
2019-02-03 15:36:08 +03:00
|
|
|
.then((results) => {
|
|
|
|
const current = results[0];
|
|
|
|
const previous = results[1];
|
|
|
|
|
|
|
|
const changed = model._changed ? Object.keys(model._changed) : {};
|
|
|
|
|
|
|
|
const payload = {
|
|
|
|
[docName.replace(/s$/, '')]: {
|
|
|
|
current: current,
|
|
|
|
previous: _.pick(previous, changed)
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
return payload;
|
|
|
|
});
|
|
|
|
};
|