[Express] Level 5: Route Instance -- refactor the code
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的更多相关文章
- [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 ...
- [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 ...
- [Express] Level 1: First Step
Installing Express Let's start building our new Express application by installing Express. Type the ...
- [Express] Level 2: Middleware -- 1
Mounting Middleware Given an application instance is set to the app variable, which of the following ...
- [Express] Level 4: Body-parser -- Delete
Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...
- [Express] Level 4: Body-parser -- Post
Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express applic ...
- [Express] Level 3: Massaging User Data
Flexible Routes Our current route only works when the city name argument matches exactly the propert ...
- [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 ...
- [Express] Level 2: Middleware -- 2
Logging Middleware Help finish the following middleware code in the logger.js file: On the response ...
随机推荐
- memset()实现及细节
memset是计算机中C/C++语言函数.将s所指向的某一块内存中的前n个 字节的内容全部设置为ch指定的ASCII值, 块的大小由第三个参数指定,这个函数通常为新申请的内存做初始化工作, 其返回值为 ...
- jQuery Mobile 页面事件总结
一.页面初始化事件(Page initiallization) 在页面创建前,当页面创建时,以及在页面初始化之后.只在第一次加载时执行. 1. pagebeforecreate 页面创建前 [sour ...
- C#/.net给textbox添加回车事件
前端js代码,放到<head>标签下 <script type="text/javascript"> function EnterTextBox(butto ...
- [Lua]入门教程
什么是Lua Lua 是一个小巧的脚本语言.是巴西里约热内卢天主教大学(Pontifical Catholic University of Rio de Janeiro)里的一个研究小组,由Rober ...
- BITED-Windows8应用开发学习札记之三:如何在Win8应用中实现数据绑定
在微软官方提供的资源中,我们可以看到SampleDataSource.cs已经拥有了定义好了相应的数据结构以及实现类: 建立本地数据 由于我们已经有数据以及相应的数据类,我们需要做的仅仅是将数据放进数 ...
- [转] Web前端优化之 CSS篇
原文链接: http://lunax.info/archives/3097.html Web 前端优化最佳实践第四部分面向 CSS.目前共计有 6 条实践规则.另请参见 Mozilla 开发者中心的文 ...
- android读取data下得数据
拥有Root权限的情况 adb shell su cd /data/data/com.package 然后就可以直接读取 没有Root的情况 adb shell run-as com.package ...
- iOS9对SDK的影响(iOS9适配必看)
1.大部分社交平台接口不支持https协议. 问题描述:在iOS9下,系统默认会拦截对http协议接口的访问,因此无法获取http协议接口的数据.对ShareSDK来说,具体表现可能是,无法授权. ...
- C#应用Newtonsoft.Json操作json[2]-反序列化不定类型
在读json时,有时不知道对方的数据类型是什么样的,本文用Newtonsoft,把json反序列化为List>,在某种情况下还是有用的. private static List<Dicti ...
- spring 解析配置文件问题
问题描述 2014-02-25 16:39:36.068 [com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2] WARN ...