| 1 |
import assert from "../../assert"; |
| 2 |
import BaseShorthandRouteHandler from "./base"; |
| 3 |
import { camelize } from "../../utils/inflector"; |
| 4 |
import Response from "../../response"; |
| 5 |
|
| 6 |
/** |
| 7 |
* @hide |
| 8 |
*/ |
| 9 |
export default class DeleteShorthandRouteHandler extends BaseShorthandRouteHandler { |
| 10 |
/* |
| 11 |
Remove the model from the db of type *camelizedModelName*. |
| 12 |
|
| 13 |
This would remove the user with id :id: |
| 14 |
Ex: this.del('/contacts/:id', 'user'); |
| 15 |
*/ |
| 16 |
handleStringShorthand(request, modelClass) { |
| 17 |
let modelName = this.shorthand; |
| 18 |
let camelizedModelName = camelize(modelName); |
| 19 |
assert( |
| 20 |
modelClass, |
| 21 |
`The route handler for ${request.url} is trying to access the ${camelizedModelName} model, but that model doesn't exist.` |
| 22 |
); |
| 23 |
|
| 24 |
let id = this._getIdForRequest(request); |
| 25 |
let model = modelClass.find(id); |
| 26 |
if (!model) { |
| 27 |
return new Response(404); |
| 28 |
} |
| 29 |
|
| 30 |
model.destroy(); |
| 31 |
} |
| 32 |
|
| 33 |
/* |
| 34 |
Remove the model and child related models from the db. |
| 35 |
|
| 36 |
This would remove the contact with id `:id`, as well |
| 37 |
as this contact's addresses and phone numbers. |
| 38 |
Ex: this.del('/contacts/:id', ['contact', 'addresses', 'numbers'); |
| 39 |
*/ |
| 40 |
handleArrayShorthand(request, modelClasses) { |
| 41 |
let id = this._getIdForRequest(request); |
| 42 |
|
| 43 |
let parent = modelClasses[0].find(id); |
| 44 |
let childTypes = modelClasses |
| 45 |
.slice(1) |
| 46 |
.map((modelClass) => |
| 47 |
this._container.inflector.pluralize(modelClass.camelizedModelName) |
| 48 |
); |
| 49 |
|
| 50 |
// Delete related children |
| 51 |
childTypes.forEach((type) => parent[type].destroy()); |
| 52 |
parent.destroy(); |
| 53 |
} |
| 54 |
} |