Deleting a region is simple, except that you must check beforehand whether the region has any cities or not. We could solve this by implementing a cascading deletion so that when you delete a region, all of its cities get deleted as well, or we may forbid the deletion outright. In our case, I opted for the latter, but it could be argued that the former is also valid, and would require not very complex logic:
// Source file: src/restful_regions.js
const deleteRegion = async (
res: any,
dbConn: any,
country: string,
region: string
) => {
try {
res.set("Connection", "close");
const sqlCities = `
SELECT 1 FROM cities
WHERE countryCode=?
AND regionCode=?
LIMIT 1
`;
const cities = await dbConn.query(sqlCities, [country, region]);
if (cities.length > 0) {
res.status(405).send("Cannot delete a region with cities");
return;
}
const deleteRegion = `
DELETE FROM regions
WHERE countryCode=?
AND regionCode=?
`;
const result = await dbConn.query(deleteRegion, [country, region]);
if (result.info.affectedRows > 0) {
res.status(204).send();
} else {
res.status(404).send("Region not found");
}
} catch (e) {
res.status(500).send("Server error");
}
};
We can test this in a similar way. Deleting a region without cities works, while attempting to do it for a region with cities or for a non-existing region fails:
> curl localhost:8080/regions/uy/23 -X DELETE --verbose
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> DELETE /regions/uy/23 HTTP/1.1
.
.
.
< HTTP/1.1 204 No Content
> curl localhost:8080/regions/uy/10 -X DELETE --verbose
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> DELETE /regions/uy/10 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.59.0
> Accept: */*
>
< HTTP/1.1 405 Method Not Allowed
.
.
.
Cannot delete a region with cities
> curl localhost:8080/regions/uy/99 --verbose
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /regions/uy/99 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.59.0
> Accept: */*
>
< HTTP/1.1 404 Not Found
.
.
.
Not found
See the different status codes that may be returned:
- 204, if a region was deleted with no problems—and in that case, no text response is sent
- 404, if the requested region doesn't exist
- 405, if the request couldn't be accepted (because the regions had cities)
Of course, you might change the workings of the service and, for example, provide for a cascading delete operation if a certain parameter was provided, as in http://some.server/regions/uy/23?cascade=true. Also, for some services, this operation may happen without even asking for it; a user might have a set of preferences, and whenever a user is to be deleted, you should also delete their preferences. This would depend on the desired semantics of the service.