Route Instance

Let's rewrite our cities routes using a Route Instance.

Create a new Route Instance for the '/cities' URL path and assign it to thecitiesRoute variable.

var citiesRoute = app.route('/cities');

Move the code from our previous app.get() route to a new GET route on the citiesRoute object.

// GET route for /cities
citiesRoute.get(function (request, response) {
if(request.query.search) {
response.json(citySearch(request.query.search));
} else {
response.json(cities);
}
});

Move app.post() to citiesRoute.

// POST route for /cities
citiesRoute.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');
}
});

Now, let's get rid of the citiesRoute temporary variable and use chaining function calls.

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');
}
});

Finally, let's move the old routes for the '/cities/:name' URL path to use the new Route Instance API.

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);
}
});

Before:

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 = {}; var citiesRoute; // GET route for /cities
app.get('/cities', function (request, response) {
if(request.query.search) {
response.json(citySearch(request.query.search));
} else {
response.json(cities);
}
}); // POST route for /cities
app.post('/cities', 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');
}
}); // GET route for /cities/:name
app.get('/cities/:name', function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo) {
response.json(cityInfo);
} else {
response.status(404).json('City not found');
}
}); // DELETE route for /cities/:name
app.delete('/cities/:name', 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);

Now:

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);

[Express] Level 5: Route Instance -- refactor the code的更多相关文章

  1. [Express] Level 5: Route file

    Using a Router Instance Let's refactor app.js to use a Router object. Create a new router object and ...

  2. [MEAN Stack] First API -- 6. Using Express route instance

    For server.js, we update the code by using route instance. By using this, we can remove some duplica ...

  3. [Express] Level 1: First Step

    Installing Express Let's start building our new Express application by installing Express. Type the ...

  4. [Express] Level 2: Middleware -- 1

    Mounting Middleware Given an application instance is set to the app variable, which of the following ...

  5. [Express] Level 4: Body-parser -- Delete

    Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...

  6. [Express] Level 4: Body-parser -- Post

    Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express applic ...

  7. [Express] Level 3: Massaging User Data

    Flexible Routes Our current route only works when the city name argument matches exactly the propert ...

  8. [Express] Level 3: Reading from the URL

    City Search We want to create an endpoint that we can use to filter cities. Follow the tasks below t ...

  9. [Express] Level 2: Middleware -- 2

    Logging Middleware Help finish the following middleware code in the logger.js file: On the response  ...

随机推荐

  1. 新手须知设计的法则 Mark

    经常看到一些讲如何学习设计的文章,坦白讲感觉有些千篇一律.且不痛不痒,都说要看点书.学点画.练软件.多观察……唉,练软件这事还要说么,难道你还需要告诉一个人学开发是需要学习编程语言的? 学习是基于过往 ...

  2. Python中list的实现

    原文链接这篇文章介绍了Python中list是如何实现的.在Python中list特别有用.让我们来看下list的内部是如何实现的.来看下面简单的程序,在list中添加一些整数并将他们打印出来. &g ...

  3. 一行 Python 实现并行化 -- 日常多线程操作的新思路

    春节坐在回家的火车上百无聊赖,偶然看到 Parallelism in one line 这篇在 Hacker News 和 reddit 上都评论过百的文章,顺手译出,enjoy:-) http:// ...

  4. Android Activity学习笔记(一)

    Activity为Android应用的四大组件之一,提供界面来与用户完成交互等操作.其中Activity的生命周期的知识这里做个笔记. Activity的生命周期由以下几个部分组成: 1.onCrea ...

  5. 【转】删除已经存在的 TFS Workspace

    删除已经存在的 TFS Workspace 分类: TFS2010-03-03 16:59 1239人阅读 评论(2) 收藏 举报 serverpathcommandcachefilegoogle 工 ...

  6. Java 理论与实践: 非阻塞算法简介——看吧,没有锁定!(转载)

    简介: Java™ 5.0 第一次让使用 Java 语言开发非阻塞算法成为可能,java.util.concurrent 包充分地利用了这个功能.非阻塞算法属于并发算法,它们可以安全地派生它们的线程, ...

  7. 自定义滚动控件(Pagecontrol)

    // // MyPageCorol.h // lejiahui // // Created by iOS开发 on 16/4/10. // Copyright © 2016年 zhongmingwuy ...

  8. 服务器资源共享--IIS站点/虚拟目录中访问共享目录(UNC)

    本文重点描述如何使用IIS访问共享资源来架设站点或执行 ASP.Net 等脚本. 通常情况下,拥有多台服务器的朋友在使用IIS建立站点的时候,会遇到如何把多台服务器的资源合并到一起的问题.如何让A服务 ...

  9. GetWindowThreadProcessId用法(转)

    函数功能:该函数返回创建指定窗口线程的标识和创建窗口的进程的标识符,后一项是可选的. 函数原型:DWORD GetWindowThreadProcessld(HWND hwnd,LPDWORD lpd ...

  10. 移动端轮播图插件(支持Zepto和jQuery)

    一. 效果图 二. 功能介绍 1. 支持图片自动轮播和非自动轮播 2. 支持点击和滑动. 三. 简单介绍 代码都有注释,逻辑简单,不做更多赘述. 1. 在你的html中添加一行. <sectio ...