Let's rewrite our cities routes using a Route Instance.
Created
May 26, 2015 19:01
-
-
Save having-fun-coding/19a620d23409fd6a2885 to your computer and use it in GitHub Desktop.
Code School | Building Blocks of Express | 5.2 Route Instance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var express = require('express'); | |
| var app = express(); | |
| var bodyParser = require('body-parser'); | |
| var parseUrlencoded = bodyParser.urlencoded({ extended: false }); | |
| // In memory store for the cities in our application | |
| var cities = {}; | |
| app.route('/cities') | |
| .get(function (request, response) { | |
| if(request.query.search) { | |
| response.json(citySearch(request.query.search)); | |
| } else { | |
| response.json(cities); | |
| } | |
| }) | |
| .post(parseUrlencoded, function (request, response) { | |
| if(request.body.description.length > 4) { | |
| var city = createCity(request.body.name, request.body.description); | |
| response.status(201).json(city); | |
| } else { | |
| response.status(400).json('Invalid City'); | |
| } | |
| }); | |
| app.route('/cities/:name') | |
| .get(function (request, response) { | |
| var cityInfo = cities[request.cityName]; | |
| if(cityInfo) { | |
| response.json(cityInfo); | |
| } else { | |
| response.status(404).json('City not found'); | |
| } | |
| }) | |
| .delete(function (request, response) { | |
| if(cities[request.cityName]) { | |
| delete cities[request.cityName]; | |
| response.sendStatus(200); | |
| } else { | |
| response.sendStatus(404); | |
| } | |
| }); | |
| // Searches for keyword in description and returns the city | |
| function citySearch(keyword) { | |
| var result = null; | |
| var search = RegExp(keyword, 'i'); | |
| for(var city in cities) { | |
| if(search.test(cities[city])) { | |
| return city; | |
| } | |
| } | |
| } | |
| // Adds a new city to the in memory store | |
| function createCity(name, description) { | |
| cities[name] = description; | |
| return name; | |
| } | |
| app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment