-
-
Notifications
You must be signed in to change notification settings - Fork 10
connect: サンプルの実装 #44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
connect: サンプルの実装 #44
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
4fbcc67
chore(npm): add connect to dependencies
azu 8f6b720
fix(connect): fix hello test
azu f1b061c
fix(connect): fix hello test
azu 16c2d23
feat(connect): add nosniff
azu 0d74a5d
fix(connect): add ; at terminal
azu 834cfa6
feat(connect): add connect example
azu 956c796
feat(connect): connectの章を追加
azu 8556137
feat(connect): インラインにmiddlewareを書いたexampleを追加
azu ff07629
feat(connect): エラーハンドリングを追加
azu e1e7e44
feat(connect): add "echo" middleware
azu 95025c6
feat(connect): add echo example
azu 506bad7
fix(connect): close server correctly
azu 629ba42
refactor(connect): closeServerを関数の中へ移動
azu e51c4a9
feat(connect): middlewareのサンプルを追加
azu c1bac2b
refactor(test): simplify mock data
azu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,7 +15,8 @@ | |
"semi": [ | ||
2, | ||
"always" | ||
] | ||
], | ||
"no-console": 0 | ||
}, | ||
"env": { | ||
"es6": true, | ||
|
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,7 @@ | ||
{ | ||
"rules": { | ||
"no-undef": 0, | ||
"no-unused-vars": 0, | ||
"no-console": 0 | ||
"no-unused-vars": 0 | ||
}, | ||
"plugins": [ | ||
"markdown" | ||
|
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
# Connect | ||
|
||
> この文章はConnect 3.4.0を元に書かれています。 | ||
|
||
[Connect](https://github.com/senchalabs/connect "Connect")はNode.jsで動くHTTPサーバフレームワークです。 | ||
_middleware_という拡張する仕組みを持っていて、connectが持つ機能自体はとても少ないです。 | ||
|
||
この章ではconnectの_middleware_の仕組みついて見て行きましょう。 | ||
|
||
## どう書ける? | ||
|
||
Connectを使った簡単なEchoサーバを書いてみましょう。 | ||
Echoサーバとは、送られてきたリクエストの内容をそのままレスポンスとして返すサーバのことです。 | ||
|
||
[import, connect-echo-example.js](../../src/connect/connect-echo-example.js) | ||
|
||
このEchoサーバに対して、以下のようなリクエストBodyを送信すると、レスポンスとして同じ値が返ってきます。 | ||
|
||
```json | ||
{ | ||
"key": "value" | ||
} | ||
``` | ||
|
||
`app.use(middleware)` という形で、_middleware_と呼ばれる関数には`request`や`response`といったオブジェクトが渡されます。 | ||
そのため、リクエストみてフィルタリングしたり、任意のレスポンスを返したり出来るようになっています。 | ||
|
||
Echoサーバでは `req.pipe(res);` という形でリクエストをそのままレスポンスとして流す事で実現されています。 | ||
|
||
### middlewareをモジュールとして実装 | ||
|
||
もう少し_middleware_をプラグインらしくモジュールとして実装したものを見てみます。 | ||
|
||
次の[connect-example.js](#connect-example.js)では、あらゆるリクエストに対して、 | ||
`"response text"`というレスポンスを`"X-Content-Type-Options"`ヘッダを付けて返すだけのものです。 | ||
|
||
それぞれの処理を_middleware_としてファイルを分けて実装し、`app.use(middleware)`で処理を追加しています。 | ||
|
||
[import errorHandler.js](../../src/connect/errorHandler.js) | ||
|
||
[import nosniff.js](../../src/connect/nosniff.js) | ||
|
||
[import hello.js](../../src/connect/hello.js) | ||
|
||
[import connect-example.js](../../src/connect/connect-example.js) | ||
|
||
基本的にどの_middleware_も`app.use(middleware)`という形で拡張でき、 | ||
モジュールとして実装すれば再利用もしやすい形となっています。 | ||
|
||
> **Note** _middleware_となる関数の引数が4つであると、それはエラーハンドリングの_middleware_とするという、connectの独自のルールがあります。 |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
"use strict"; | ||
import connect from "connect"; | ||
import http from "http"; | ||
import fetch from "node-fetch"; | ||
import assert from "assert"; | ||
var app = connect(); | ||
// add Error handling | ||
app.use(function (err, req, res, next) { | ||
console.error(err.stack); | ||
res.status(500).send(err.message); | ||
next(); | ||
}); | ||
// request to response | ||
app.use(function (req, res) { | ||
req.pipe(res); | ||
}); | ||
//create node.js http server and listen on port | ||
var server = http.createServer(app).listen(3000, request); | ||
|
||
// request => response | ||
function request() { | ||
var closeServer = server.close.bind(server); | ||
var requestBody = { | ||
"key": "value" | ||
}; | ||
fetch("http://localhost:3000", { | ||
method: "POST", | ||
body: JSON.stringify(requestBody) | ||
}) | ||
.then(res => res.text()) | ||
.then(text => { | ||
assert.deepEqual(text, requestBody); | ||
}).then(closeServer, closeServer); | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
"use strict"; | ||
import errorHandler from "./errorHandler"; | ||
import hello from "./hello"; | ||
import nosniff from "./nosniff"; | ||
import assert from "assert"; | ||
import connect from "connect"; | ||
import http from "http"; | ||
import fetch from "node-fetch"; | ||
const responseText = "response text"; | ||
var app = connect(); | ||
// add Error handling | ||
app.use(errorHandler()); | ||
// add "X-Content-Type-Options" to response | ||
app.use(nosniff()); | ||
// respond to all requests | ||
app.use(hello(responseText)); | ||
//create node.js http server and listen on port | ||
var server = http.createServer(app).listen(3000, request); | ||
|
||
function request() { | ||
var closeServer = server.close.bind(server); | ||
fetch("http://localhost:3000") | ||
.then(res => res.text()) | ||
.then(text => { | ||
assert.equal(text, responseText); | ||
server.close(); | ||
}) | ||
.catch(console.error.bind(console)) | ||
.then(closeServer, closeServer); | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
"use strict"; | ||
export default function () { | ||
return function (req, res) { | ||
req.pipe(res); | ||
}; | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
"use strict"; | ||
export default function errorHandler() { | ||
return function (err, req, res, next) { | ||
console.error(err.stack); | ||
res.status(500).send(err.message); | ||
next(); | ||
}; | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
"use strict"; | ||
export default function (text) { | ||
return function (req, res) { | ||
res.end(text); | ||
}; | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
"use strict"; | ||
function setHeaders(res, headers) { | ||
Object.keys(headers).forEach(key => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. これES6だともっとキレイに書けるような気がする… |
||
let value = headers[key]; | ||
if (value !== null) { | ||
res.setHeader(key, value); | ||
} | ||
}); | ||
} | ||
export default function () { | ||
return function (req, res, next) { | ||
setHeaders(res, { | ||
"X-Content-Type-Options": "nosniff" | ||
}); | ||
next(); | ||
}; | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
// LICENSE : MIT | ||
"use strict"; | ||
import assert from "power-assert"; | ||
import connect from "connect"; | ||
import errorHandler from "../../src/connect/errorHandler"; | ||
import nosniff from "../../src/connect/nosniff"; | ||
import hello from "../../src/connect/hello"; | ||
import echo from "../../src/connect/echo"; | ||
import http from "http"; | ||
import fetch from "node-fetch"; | ||
describe("connect", function () { | ||
var responseText = "test"; | ||
var server; | ||
describe("errorHandler", function () { | ||
beforeEach(function (done) { | ||
var app = connect(); | ||
app.use(errorHandler()); | ||
app.use((req, res, next) => { | ||
next(new Error("wrong")); | ||
}); | ||
server = http.createServer(app).listen(3000, done); | ||
}); | ||
afterEach(function () { | ||
server && server.close(); | ||
}); | ||
it("should return 500 status response", function () { | ||
return fetch("http://localhost:3000") | ||
.then(res => res.status) | ||
.then(status => { | ||
assert(status, 500); | ||
}); | ||
}); | ||
|
||
}); | ||
describe("hello", function () { | ||
beforeEach(function (done) { | ||
var app = connect(); | ||
app.use(errorHandler()); | ||
app.use(hello(responseText)); | ||
server = http.createServer(app).listen(3000, done); | ||
}); | ||
afterEach(function () { | ||
server && server.close(); | ||
}); | ||
it("should return response text", function () { | ||
return fetch("http://localhost:3000") | ||
.then(res => res.text()) | ||
.then(text => { | ||
assert.equal(text, responseText); | ||
}); | ||
}); | ||
}); | ||
describe("sniff", function () { | ||
beforeEach(function (done) { | ||
var app = connect(); | ||
app.use(nosniff()); | ||
app.use(hello(responseText)); | ||
server = http.createServer(app).listen(3000, done); | ||
}); | ||
afterEach(function () { | ||
server && server.close(); | ||
}); | ||
it("should return response has `X-Content-Type-Options` header", function () { | ||
return fetch("http://localhost:3000") | ||
.then(res => { | ||
assert.equal(res.headers.get("x-content-type-options"), "nosniff"); | ||
}); | ||
}); | ||
}); | ||
describe("echo", function () { | ||
beforeEach(function (done) { | ||
var app = connect(); | ||
app.use(echo()); | ||
server = http.createServer(app).listen(3000, done); | ||
}); | ||
afterEach(function () { | ||
server && server.close(); | ||
}); | ||
it("should return request as response", function () { | ||
var requestBody = { | ||
key: "value" | ||
}; | ||
return fetch("http://localhost:3000", { | ||
method: "POST", | ||
headers: { | ||
"Accept": "application/json", | ||
"Content-Type": "application/json" | ||
}, | ||
body: JSON.stringify(requestBody) | ||
}).then(res => { | ||
return res.json(); | ||
}).then(json => { | ||
assert.deepEqual(json, requestBody); | ||
}); | ||
}); | ||
}); | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
var
まざってるの何か統一したいなThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#45 issueを立てた