Skip to content

Instantly share code, notes, and snippets.

@having-fun-coding
Created May 24, 2015 17:09
Show Gist options
  • Select an option

  • Save having-fun-coding/37956a0d2ad64860ad82 to your computer and use it in GitHub Desktop.

Select an option

Save having-fun-coding/37956a0d2ad64860ad82 to your computer and use it in GitHub Desktop.
3.9 Dynamic Routes III
The following code has a Dynamic Route that takes a year
as an argument and returns the city created in that year.
The problem with our current implementation is that it
breaks when invalid data is sent on client requests.
Let's add some basic validation.
app.js
var express = require('express');
var app = express();
app.param('year', function(request, response, next) {
if(isYearFormat(request.params.year)) {
next();
} else {
response.status(400).json('Invalid Format for Year');
}
});
var citiesYear = {
5000: 'Lotopia',
5100: 'Caspiana',
5105: 'Indigo',
6000: 'Paradise',
7000: 'Flotilla'
};
function isYearFormat(value) {
var regexp = RegExp(/^d{4}$/);
return regexp.test(value);
}
app.get('/cities/year/:year', function(request, response) {
var year = request.params.year;
var city = citiesYear[year];
if(!city) {
response.status(404).json("No City found for given year");
} else {
response.json("In " + year + ", " + city + " is created.");
}
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment