Created
January 30, 2019 09:54
-
-
Save tikijian/04cd76840900a63c1a055d06114a87c1 to your computer and use it in GitHub Desktop.
sails.js destroy blueprint override
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Это копия стандартного sails blueprint destroy action | |
// за исключением того, что по дефолту вызывается .meta(fetch: true) | |
// для того, чтобы вызывались afterDestroy колбеки моделей. | |
// переопределение возможно за счет пакета https://github.com/sgress454/sails-hook-custom-blueprints | |
// подробней в моем issue https://github.com/balderdashy/sails/issues/4476 | |
// Если issue пофиксят в мою пользу, то это переопределение можно будет убрать | |
var _ = require('@sailshq/lodash'); | |
module.exports = function destroyOneRecord (req, res) { | |
var parseBlueprintOptions = req.options.parseBlueprintOptions || req._sails.config.blueprints.parseBlueprintOptions; | |
// Set the blueprint action for parseBlueprintOptions. | |
req.options.blueprintAction = 'destroy'; | |
var queryOptions = parseBlueprintOptions(req); | |
var Model = req._sails.models[queryOptions.using]; | |
var criteria = {}; | |
criteria[Model.primaryKey] = queryOptions.criteria.where[Model.primaryKey]; | |
var query = Model.findOne(_.cloneDeep(criteria), queryOptions.populates).meta(queryOptions.meta); | |
query.exec(function foundRecord (err, record) { | |
if (err) { | |
// If this is a usage error coming back from Waterline, | |
// (e.g. a bad criteria), then respond w/ a 400 status code. | |
// Otherwise, it's something unexpected, so use 500. | |
switch (err.name) { | |
case 'UsageError': return res.badRequest(err.message); | |
default: return res.serverError(err); | |
} | |
}//-• | |
if(!record) { return res.notFound('No record found with the specified `id`.'); } | |
Model.destroy(_.cloneDeep(criteria)).meta({fetch: true}).exec(function destroyedRecord (err) { | |
if (err) { | |
switch (err.name) { | |
case 'UsageError': return res.badRequest(err.message); | |
default: return res.serverError(err); | |
} | |
}//-• | |
return res.ok(record); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment