Handling PUTs

A PUT request means that an existing resource is to be updated. In our case, a pre-condition is that the specified region must exist; otherwise, a 404 error would be appropriate. If the region exists, then we can update it and send a 204 status. If MySQL detects that no changes have been made to the region, it lets you know that the UPDATE didn't change anything; you could either send a 204 (as I chose to) or a 409 error, but in any case, you are certain that the region has the data you want. We'll also have to do some parameter checking; in this case, just to make sure that a name is given, but the data validation logic could be much more complex:

// Source file: src/restful_regions.js

const putRegion = async (
res: any,
dbConn: any,
country: string,
region: string,
name: string
) => {
res.set("Connection", "close");

if (!name) {
res.status(400).send("Missing name");
return;
}

try {
const sqlUpdateRegion = `
UPDATE regions
SET regionName=?
WHERE countryCode=?
AND regionCode=?
`;

const result = await dbConn.query(sqlUpdateRegion, [
name,
country,
region
]);

if (result.info.affectedRows > 0) {
res.status(204).send();
} else {
res.status(409).send("Region not updated");
}
} catch (e) {
res.status(500).send("Server error");
}
};

This is easy to test, since there are only two situations (either the region exists or it doesn't), plus a sanity check in case the name is missing. Let's add the missing tilde to a region first; just like before, no content will be received because of the 204 status code:

> curl localhost:8080/regions/uy/16 -X PUT -d "name=San Jose" --verbose 
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> PUT /regions/uy/16 HTTP/1.1
.
.
.
< HTTP/1.1 204 No Content

The two error cases (non-existent region, missing name) are quickly taken care of. The former case is detected by MySQL, while the latter is caught by the initial if statement:

> curl localhost:8080/regions/uy/xyzzy -X PUT -d "name=Colossal Cave" --verbose           
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> PUT /regions/uy/xyzzy HTTP/1.1
.
.

.
< HTTP/1.1 409 Conflict
.
.

.
Region not updated

> curl localhost:8080/regions/uy/10 -X PUT --verbose
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> PUT /regions/uy/10 HTTP/1.1
.
.

.
< HTTP/1.1 400 Bad Request
.
.

.
Missing name

Handling PUT is just about the simplest case; let's finish our study of the server by taking a close look at the most complex request, a POST.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset