🐛 Fixed a 500 error for incorrect fields parameter in API

refs 8a1fd1f57f
refs 5584430ddc

- The change to async/await in the original commit 558443 was causing problems in downstream dependencies (create-error package) where it was loosing a context of "this". It's not a direct dependency so I didn't go yak shaving into where exacly the context is lost.
- The fix to keep a correct context of "this" was sticking to an existing pattern using regular function returning promises. Once we need to redo them into async/await we can investigate if there's a way around create-error's context prolbem
This commit is contained in:
Naz 2021-07-06 11:58:14 +04:00
parent ec7cf99279
commit 2c1ae2e9af
3 changed files with 26 additions and 3 deletions

View File

@ -1,6 +1,12 @@
const _ = require('lodash');
const errors = require('@tryghost/errors');
const tpl = require('@tryghost/tpl');
const messages = {
couldNotUnderstandRequest: 'Could not understand request.'
};
/**
* @param {Bookshelf} Bookshelf
*/
@ -131,7 +137,18 @@ module.exports = function (Bookshelf) {
options.columns = _.intersection(options.columns, this.prototype.permittedAttributes());
}
return model.fetch(options);
return model.fetch(options)
.catch((err) => {
// CASE: SQL syntax is incorrect
if (err.errno === 1054 || err.errno === 1) {
throw new errors.BadRequestError({
message: tpl(messages.couldNotUnderstandRequest),
err
});
}
throw err;
});
},
/**

View File

@ -283,6 +283,14 @@ describe('Posts API (canary)', function () {
done();
});
});
it('throws a 400 when a non-existing field is requested', async function () {
await request.get(localUtils.API.getApiQuery(`posts/slug/${testUtils.DataGenerator.Content.posts[0].slug}/?fields=tags`))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(400);
});
});
describe('Add', function () {

View File

@ -89,8 +89,6 @@ describe('Models: crud', function () {
const findOneReturnValue = models.Base.Model.findOne(data, unfilteredOptions);
should.equal(findOneReturnValue, fetchStub.returnValues[0]);
return findOneReturnValue.then((result) => {
should.equal(result, fetchedModel);