Handling POSTs

Finally, handling POST requests is a bit more complex, since you are supposed to say to which collection (in this case, a country's) you want to add the new resource, and the logic is supposed to do everything, including assigning an ID. This means that our code will be a bit longer, since we'll be adding the need to find an unused region code. There will be another difference: when the resource is created, the URI for the new resource should be returned in the Location header, so that will be another extra requirement.

Finally, once again, we'll have some data validation, as with PUT requests:

// Source file: src/restful_regions.js

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

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

try {
const sqlCountry = `
SELECT 1
FROM countries
WHERE countryCode=?
`;
const countries = await dbConn.query(sqlCountry, [country]);
if (countries.length === 0) {
res.status(403).send("Country must exist");
return;
}

const sqlGetId = `
SELECT MAX(CAST(regionCode AS INTEGER)) AS maxr
FROM regions
WHERE countryCode=?
`;
const regions = await dbConn.query(sqlGetId, [country]);
const newId =
regions.length === 0 ? 1 : 1 + Number(regions[0].maxr);

const sqlAddRegion = `
INSERT INTO regions SET
countryCode=?,
regionCode=?,
regionName=?
`;

const result = await dbConn.query(sqlAddRegion, [
country,
newId,
name
]);
if (result.info.affectedRows > 0) {
res.status(201)
.header("Location", `/regions/${country}/${newId}`)
.send("Region created");
} else {
res.status(409).send("Region not created");
}
} catch (e) {
res.status(500).send("Server error");
}
};

This is the logic that requires the most queries. We must (1) check that the country exists, (2) determine the maximum region ID for that country, and only then (3) insert the new region and return a 201 status to the user. We can test this in a similar way to what we did for PUT, so let's look at a simple case:

> curl localhost:8080/regions/ar -X POST -d "name=NEW REGION" --verbose 
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> POST /regions/ar HTTP/1.1
.
.
.

< HTTP/1.1 201 Created
< X-Powered-By: Express
< Location: /regions/ar/25
.
.
.
Region created

> curl localhost:8080/regions/ar/25

[{"countryCode":"ar","regionCode":"25","regionName":"NEW REGION"}]

Argentina has 24 provinces, numbered from 1 to 24 in the regions table, so if we add a new one, it should be #25, and the Location header in the answer proves that this is so. (We are only returning the route, without the server and port, but we could easily add those pieces of data.) Doing a GET confirms that the POST succeeded.

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

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