Ghost/core/server/api/canary/posts.js

264 lines
8.3 KiB
JavaScript
Raw Normal View History

const models = require('../../models');
Refactored `common` lib import to use destructuring (#11835) * refactored `core/frontend/apps` to destructure common imports * refactored `core/frontend/services/{apps, redirects, routing}` to destructure common imports * refactored `core/frontend/services/settings` to destructure common imports * refactored remaining `core/frontend/services` to destructure common imports * refactored `core/server/adapters` to destructure common imports * refactored `core/server/data/{db, exporter, schema, validation}` to destructure common imports * refactored `core/server/data/importer` to destructure common imports * refactored `core/server/models/{base, plugins, relations}` to destructure common imports * refactored remaining `core/server/models` to destructure common imports * refactored `core/server/api/canary/utils/serializers/output` to destructure common imports * refactored remaining `core/server/api/canary/utils` to destructure common imports * refactored remaining `core/server/api/canary` to destructure common imports * refactored `core/server/api/shared` to destructure common imports * refactored `core/server/api/v2/utils` to destructure common imports * refactored remaining `core/server/api/v2` to destructure common imports * refactored `core/frontend/meta` to destructure common imports * fixed some tests referencing `common.errors` instead of `@tryghost/errors` - Not all of them need to be updated; only updating the ones that are causing failures * fixed errors import being shadowed by local scope
2020-05-22 21:22:20 +03:00
const {i18n} = require('../../lib/common');
const errors = require('@tryghost/errors');
const urlUtils = require('../../../shared/url-utils');
const {mega} = require('../../services/mega');
const membersService = require('../../services/members');
const allowedIncludes = ['tags', 'authors', 'authors.roles', 'email'];
const unsafeAttrs = ['status', 'authors', 'visibility'];
module.exports = {
docName: 'posts',
browse: {
options: [
'include',
'filter',
'fields',
'formats',
'limit',
'order',
'page',
'debug',
'absolute_urls'
],
validation: {
options: {
include: {
values: allowedIncludes
},
formats: {
values: models.Post.allowedFormats
}
}
},
permissions: {
unsafeAttrs: unsafeAttrs
},
query(frame) {
return models.Post.findPage(frame.options);
}
},
read: {
options: [
'include',
'fields',
'formats',
'debug',
'absolute_urls',
// NOTE: only for internal context
'forUpdate',
'transacting'
],
data: [
'id',
'slug',
'uuid'
],
validation: {
options: {
include: {
values: allowedIncludes
},
formats: {
values: models.Post.allowedFormats
}
}
},
permissions: {
unsafeAttrs: unsafeAttrs
},
query(frame) {
return models.Post.findOne(frame.data, frame.options)
.then((model) => {
if (!model) {
Refactored `common` lib import to use destructuring (#11835) * refactored `core/frontend/apps` to destructure common imports * refactored `core/frontend/services/{apps, redirects, routing}` to destructure common imports * refactored `core/frontend/services/settings` to destructure common imports * refactored remaining `core/frontend/services` to destructure common imports * refactored `core/server/adapters` to destructure common imports * refactored `core/server/data/{db, exporter, schema, validation}` to destructure common imports * refactored `core/server/data/importer` to destructure common imports * refactored `core/server/models/{base, plugins, relations}` to destructure common imports * refactored remaining `core/server/models` to destructure common imports * refactored `core/server/api/canary/utils/serializers/output` to destructure common imports * refactored remaining `core/server/api/canary/utils` to destructure common imports * refactored remaining `core/server/api/canary` to destructure common imports * refactored `core/server/api/shared` to destructure common imports * refactored `core/server/api/v2/utils` to destructure common imports * refactored remaining `core/server/api/v2` to destructure common imports * refactored `core/frontend/meta` to destructure common imports * fixed some tests referencing `common.errors` instead of `@tryghost/errors` - Not all of them need to be updated; only updating the ones that are causing failures * fixed errors import being shadowed by local scope
2020-05-22 21:22:20 +03:00
throw new errors.NotFoundError({
message: i18n.t('errors.api.posts.postNotFound')
});
}
return model;
});
}
},
add: {
statusCode: 201,
headers: {},
options: [
'include',
'formats',
Updated newsletter functionality to use `email_recipient_filter` (#12343) no-issue * Used email_recipient_filter in MEGA This officially decouples the newsletter recipients from the post visibility allowing us to send emails to free members only * Supported enum for send_email_when_published in model This allows us to migrate from the previously used boolean to an enum when we eventually rename the email_recipient_filter column to send_email_when_published * Updated the posts API to handle email_recipient_filter We now no longer rely on the send_email_when_published property to send newsletters, meaning we can remove the column and start cleaning up the new columns name * Handled draft status changes when emails not sent We want to reset any concept of sending an email when a post is transition to the draft status, if and only if, and email has not already been sent. If an email has been sent, we should leave the email related fields as they were. * Removed send_email_when_published from add method This is not supported at the model layer * Removed email_recipient_filter from v2&Content API This should not be exposed on previous api versions, or publicly * Removed reference to send_email_when_published This allows us to move completely to the email_recipient_filter property, keeping the code clean and allowing us to delete the send_email_when_published column in the database. We plan to then migrate _back_ to the send_email_when_published name at both the database and api level.
2020-11-06 20:32:23 +03:00
'source'
],
validation: {
options: {
include: {
values: allowedIncludes
},
source: {
values: ['html']
}
}
},
permissions: {
unsafeAttrs: unsafeAttrs
},
query(frame) {
return models.Post.add(frame.data.posts[0], frame.options)
.then((model) => {
if (model.get('status') !== 'published') {
this.headers.cacheInvalidate = false;
} else {
this.headers.cacheInvalidate = true;
}
return model;
});
}
},
edit: {
headers: {},
options: [
'include',
'id',
'formats',
'source',
Updated newsletter functionality to use `email_recipient_filter` (#12343) no-issue * Used email_recipient_filter in MEGA This officially decouples the newsletter recipients from the post visibility allowing us to send emails to free members only * Supported enum for send_email_when_published in model This allows us to migrate from the previously used boolean to an enum when we eventually rename the email_recipient_filter column to send_email_when_published * Updated the posts API to handle email_recipient_filter We now no longer rely on the send_email_when_published property to send newsletters, meaning we can remove the column and start cleaning up the new columns name * Handled draft status changes when emails not sent We want to reset any concept of sending an email when a post is transition to the draft status, if and only if, and email has not already been sent. If an email has been sent, we should leave the email related fields as they were. * Removed send_email_when_published from add method This is not supported at the model layer * Removed email_recipient_filter from v2&Content API This should not be exposed on previous api versions, or publicly * Removed reference to send_email_when_published This allows us to move completely to the email_recipient_filter property, keeping the code clean and allowing us to delete the send_email_when_published column in the database. We plan to then migrate _back_ to the send_email_when_published name at both the database and api level.
2020-11-06 20:32:23 +03:00
'email_recipient_filter',
Fixed backward compatibility for `send_email_when_published` (#12357) no-issue * Handled send_email_when_published in Posts API This restores backwards compatibility of the Posts API allowing existing clients to continue to use the `send_email_when_published` flag. This change uses two edits, which is unfortunate. The reason being is that this is an API compatibility issue, not a model issue, so we shouldn't introduce code to the model layer to handle it. The visibility property of the model is used to determine how to fall back, and because it can be left out of the API request, and relies on a default in the settings, we require that the model decide on the `visibility` before we run our fallback logic (or we duplicate the `visibility` default at the cost of maintenance in the future) * Dropped send_email_when_published column from posts Since this column is not used any more, we can drop it from the table. We include an extra migration to repopulate the column in the event of a rollback * Updated importer to handle send_email_when_published Because we currently export this value from Ghost, we should correctly import it. This follows the same logic as the migrations for this value. * Included send_email_when_published in API response As our v3 API documentation includes `send_email_when_published` we must retain backward compatibility by calculating the property. * Fixed fields filter with send_email_when_published * Added safety checks to frame properties Some parts of the code pass a manually created "frame" which is missing lots of properties, so we check for the existence of all of them before using them. * Fixed 3.1 migration to include columnDefinition We require that migrations have all the information they need contained within them as they run in an unknown state of the codebase, which could be from the commit they are introduced, to any future commit. In this case the column definition is removed from the schema in 3.38 and the migration would fail when run in this version or later.
2020-11-11 16:03:41 +03:00
'send_email_when_published',
'force_rerender',
// NOTE: only for internal context
'forUpdate',
'transacting'
],
validation: {
options: {
include: {
values: allowedIncludes
},
id: {
required: true
},
source: {
values: ['html']
Updated newsletter functionality to use `email_recipient_filter` (#12343) no-issue * Used email_recipient_filter in MEGA This officially decouples the newsletter recipients from the post visibility allowing us to send emails to free members only * Supported enum for send_email_when_published in model This allows us to migrate from the previously used boolean to an enum when we eventually rename the email_recipient_filter column to send_email_when_published * Updated the posts API to handle email_recipient_filter We now no longer rely on the send_email_when_published property to send newsletters, meaning we can remove the column and start cleaning up the new columns name * Handled draft status changes when emails not sent We want to reset any concept of sending an email when a post is transition to the draft status, if and only if, and email has not already been sent. If an email has been sent, we should leave the email related fields as they were. * Removed send_email_when_published from add method This is not supported at the model layer * Removed email_recipient_filter from v2&Content API This should not be exposed on previous api versions, or publicly * Removed reference to send_email_when_published This allows us to move completely to the email_recipient_filter property, keeping the code clean and allowing us to delete the send_email_when_published column in the database. We plan to then migrate _back_ to the send_email_when_published name at both the database and api level.
2020-11-06 20:32:23 +03:00
},
email_recipient_filter: {
values: ['none', 'free', 'paid', 'all']
Fixed backward compatibility for `send_email_when_published` (#12357) no-issue * Handled send_email_when_published in Posts API This restores backwards compatibility of the Posts API allowing existing clients to continue to use the `send_email_when_published` flag. This change uses two edits, which is unfortunate. The reason being is that this is an API compatibility issue, not a model issue, so we shouldn't introduce code to the model layer to handle it. The visibility property of the model is used to determine how to fall back, and because it can be left out of the API request, and relies on a default in the settings, we require that the model decide on the `visibility` before we run our fallback logic (or we duplicate the `visibility` default at the cost of maintenance in the future) * Dropped send_email_when_published column from posts Since this column is not used any more, we can drop it from the table. We include an extra migration to repopulate the column in the event of a rollback * Updated importer to handle send_email_when_published Because we currently export this value from Ghost, we should correctly import it. This follows the same logic as the migrations for this value. * Included send_email_when_published in API response As our v3 API documentation includes `send_email_when_published` we must retain backward compatibility by calculating the property. * Fixed fields filter with send_email_when_published * Added safety checks to frame properties Some parts of the code pass a manually created "frame" which is missing lots of properties, so we check for the existence of all of them before using them. * Fixed 3.1 migration to include columnDefinition We require that migrations have all the information they need contained within them as they run in an unknown state of the codebase, which could be from the commit they are introduced, to any future commit. In this case the column definition is removed from the schema in 3.38 and the migration would fail when run in this version or later.
2020-11-11 16:03:41 +03:00
},
send_email_when_published: {
values: [true, false]
}
}
},
permissions: {
unsafeAttrs: unsafeAttrs
},
async query(frame) {
/**Check host limits for members when send email is true**/
Fixed backward compatibility for `send_email_when_published` (#12357) no-issue * Handled send_email_when_published in Posts API This restores backwards compatibility of the Posts API allowing existing clients to continue to use the `send_email_when_published` flag. This change uses two edits, which is unfortunate. The reason being is that this is an API compatibility issue, not a model issue, so we shouldn't introduce code to the model layer to handle it. The visibility property of the model is used to determine how to fall back, and because it can be left out of the API request, and relies on a default in the settings, we require that the model decide on the `visibility` before we run our fallback logic (or we duplicate the `visibility` default at the cost of maintenance in the future) * Dropped send_email_when_published column from posts Since this column is not used any more, we can drop it from the table. We include an extra migration to repopulate the column in the event of a rollback * Updated importer to handle send_email_when_published Because we currently export this value from Ghost, we should correctly import it. This follows the same logic as the migrations for this value. * Included send_email_when_published in API response As our v3 API documentation includes `send_email_when_published` we must retain backward compatibility by calculating the property. * Fixed fields filter with send_email_when_published * Added safety checks to frame properties Some parts of the code pass a manually created "frame" which is missing lots of properties, so we check for the existence of all of them before using them. * Fixed 3.1 migration to include columnDefinition We require that migrations have all the information they need contained within them as they run in an unknown state of the codebase, which could be from the commit they are introduced, to any future commit. In this case the column definition is removed from the schema in 3.38 and the migration would fail when run in this version or later.
2020-11-11 16:03:41 +03:00
if ((frame.options.email_recipient_filter && frame.options.email_recipient_filter !== 'none') || frame.options.send_email_when_published) {
await membersService.checkHostLimit();
}
let model;
Fixed backward compatibility for `send_email_when_published` (#12357) no-issue * Handled send_email_when_published in Posts API This restores backwards compatibility of the Posts API allowing existing clients to continue to use the `send_email_when_published` flag. This change uses two edits, which is unfortunate. The reason being is that this is an API compatibility issue, not a model issue, so we shouldn't introduce code to the model layer to handle it. The visibility property of the model is used to determine how to fall back, and because it can be left out of the API request, and relies on a default in the settings, we require that the model decide on the `visibility` before we run our fallback logic (or we duplicate the `visibility` default at the cost of maintenance in the future) * Dropped send_email_when_published column from posts Since this column is not used any more, we can drop it from the table. We include an extra migration to repopulate the column in the event of a rollback * Updated importer to handle send_email_when_published Because we currently export this value from Ghost, we should correctly import it. This follows the same logic as the migrations for this value. * Included send_email_when_published in API response As our v3 API documentation includes `send_email_when_published` we must retain backward compatibility by calculating the property. * Fixed fields filter with send_email_when_published * Added safety checks to frame properties Some parts of the code pass a manually created "frame" which is missing lots of properties, so we check for the existence of all of them before using them. * Fixed 3.1 migration to include columnDefinition We require that migrations have all the information they need contained within them as they run in an unknown state of the codebase, which could be from the commit they are introduced, to any future commit. In this case the column definition is removed from the schema in 3.38 and the migration would fail when run in this version or later.
2020-11-11 16:03:41 +03:00
if (!frame.options.email_recipient_filter && frame.options.send_email_when_published) {
await models.Base.transaction(async (transacting) => {
const options = {
...frame.options,
transacting
};
/**
* 1. We need to edit the post first in order to know what the visibility is.
* 2. We can only pass the email_recipient_filter when we change the status.
*
* So, we first edit the post as requested, with all information except the status,
* from there we can determine what the email_recipient_filter should be and then finish
* the edit, with the status and the email_recipient_filter option.
*/
const status = frame.data.posts[0].status;
delete frame.data.posts[0].status;
const interimModel = await models.Post.edit(frame.data.posts[0], options);
frame.data.posts[0].status = status;
options.email_recipient_filter = interimModel.get('visibility') === 'paid' ? 'paid' : 'all';
model = await models.Post.edit(frame.data.posts[0], options);
});
} else {
Fixed backward compatibility for `send_email_when_published` (#12357) no-issue * Handled send_email_when_published in Posts API This restores backwards compatibility of the Posts API allowing existing clients to continue to use the `send_email_when_published` flag. This change uses two edits, which is unfortunate. The reason being is that this is an API compatibility issue, not a model issue, so we shouldn't introduce code to the model layer to handle it. The visibility property of the model is used to determine how to fall back, and because it can be left out of the API request, and relies on a default in the settings, we require that the model decide on the `visibility` before we run our fallback logic (or we duplicate the `visibility` default at the cost of maintenance in the future) * Dropped send_email_when_published column from posts Since this column is not used any more, we can drop it from the table. We include an extra migration to repopulate the column in the event of a rollback * Updated importer to handle send_email_when_published Because we currently export this value from Ghost, we should correctly import it. This follows the same logic as the migrations for this value. * Included send_email_when_published in API response As our v3 API documentation includes `send_email_when_published` we must retain backward compatibility by calculating the property. * Fixed fields filter with send_email_when_published * Added safety checks to frame properties Some parts of the code pass a manually created "frame" which is missing lots of properties, so we check for the existence of all of them before using them. * Fixed 3.1 migration to include columnDefinition We require that migrations have all the information they need contained within them as they run in an unknown state of the codebase, which could be from the commit they are introduced, to any future commit. In this case the column definition is removed from the schema in 3.38 and the migration would fail when run in this version or later.
2020-11-11 16:03:41 +03:00
model = await models.Post.edit(frame.data.posts[0], frame.options);
}
/**Handle newsletter email */
Updated newsletter functionality to use `email_recipient_filter` (#12343) no-issue * Used email_recipient_filter in MEGA This officially decouples the newsletter recipients from the post visibility allowing us to send emails to free members only * Supported enum for send_email_when_published in model This allows us to migrate from the previously used boolean to an enum when we eventually rename the email_recipient_filter column to send_email_when_published * Updated the posts API to handle email_recipient_filter We now no longer rely on the send_email_when_published property to send newsletters, meaning we can remove the column and start cleaning up the new columns name * Handled draft status changes when emails not sent We want to reset any concept of sending an email when a post is transition to the draft status, if and only if, and email has not already been sent. If an email has been sent, we should leave the email related fields as they were. * Removed send_email_when_published from add method This is not supported at the model layer * Removed email_recipient_filter from v2&Content API This should not be exposed on previous api versions, or publicly * Removed reference to send_email_when_published This allows us to move completely to the email_recipient_filter property, keeping the code clean and allowing us to delete the send_email_when_published column in the database. We plan to then migrate _back_ to the send_email_when_published name at both the database and api level.
2020-11-06 20:32:23 +03:00
if (model.get('email_recipient_filter') !== 'none') {
const postPublished = model.wasChanged() && (model.get('status') === 'published') && (model.previous('status') !== 'published');
if (postPublished) {
let postEmail = model.relations.email;
if (!postEmail) {
const email = await mega.addEmail(model, frame.options);
model.set('email', email);
} else if (postEmail && postEmail.get('status') === 'failed') {
const email = await mega.retryFailedEmail(postEmail);
model.set('email', email);
}
}
}
/**Handle cache invalidation */
if (
model.get('status') === 'published' && model.wasChanged() ||
model.get('status') === 'draft' && model.previous('status') === 'published'
) {
this.headers.cacheInvalidate = true;
} else if (
model.get('status') === 'draft' && model.previous('status') !== 'published' ||
model.get('status') === 'scheduled' && model.wasChanged()
) {
this.headers.cacheInvalidate = {
value: urlUtils.urlFor({
relativeUrl: urlUtils.urlJoin('/p', model.get('uuid'), '/')
})
};
} else {
this.headers.cacheInvalidate = false;
}
return model;
}
},
destroy: {
statusCode: 204,
headers: {
cacheInvalidate: true
},
options: [
'include',
'id'
],
validation: {
options: {
include: {
values: allowedIncludes
},
id: {
required: true
}
}
},
permissions: {
unsafeAttrs: unsafeAttrs
},
query(frame) {
frame.options.require = true;
return models.Post.destroy(frame.options)
.then(() => null)
.catch(models.Post.NotFoundError, () => {
Refactored `common` lib import to use destructuring (#11835) * refactored `core/frontend/apps` to destructure common imports * refactored `core/frontend/services/{apps, redirects, routing}` to destructure common imports * refactored `core/frontend/services/settings` to destructure common imports * refactored remaining `core/frontend/services` to destructure common imports * refactored `core/server/adapters` to destructure common imports * refactored `core/server/data/{db, exporter, schema, validation}` to destructure common imports * refactored `core/server/data/importer` to destructure common imports * refactored `core/server/models/{base, plugins, relations}` to destructure common imports * refactored remaining `core/server/models` to destructure common imports * refactored `core/server/api/canary/utils/serializers/output` to destructure common imports * refactored remaining `core/server/api/canary/utils` to destructure common imports * refactored remaining `core/server/api/canary` to destructure common imports * refactored `core/server/api/shared` to destructure common imports * refactored `core/server/api/v2/utils` to destructure common imports * refactored remaining `core/server/api/v2` to destructure common imports * refactored `core/frontend/meta` to destructure common imports * fixed some tests referencing `common.errors` instead of `@tryghost/errors` - Not all of them need to be updated; only updating the ones that are causing failures * fixed errors import being shadowed by local scope
2020-05-22 21:22:20 +03:00
return Promise.reject(new errors.NotFoundError({
message: i18n.t('errors.api.posts.postNotFound')
}));
});
}
}
};