Repository: yvele/azure-function-express
Branch: master
Commit: 349ae0b07035
Files: 30
Total size: 49.0 KB
Directory structure:
gitextract_in6ieqkr/
├── .babelrc.js
├── .editorconfig
├── .eslintrc.js
├── .gitattributes
├── .gitignore
├── .nvmrc
├── .travis.yml
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── docs/
│ └── azure-function.md
├── examples/
│ ├── all-routes/
│ │ ├── function.json
│ │ └── index.js
│ ├── basic/
│ │ ├── function.json
│ │ └── index.js
│ └── basic-module/
│ ├── function.json
│ └── index.js
├── package.json
├── src/
│ ├── ExpressAdapter.js
│ ├── IncomingMessage.js
│ ├── OutgoingMessage.js
│ ├── createAzureFunctionHandler.js
│ ├── index.js
│ └── statusCodes.js
└── test/
├── ExpressAdapter.test.js
├── IncomingMessage.test.js
├── OutgoingMessage.test.js
├── expressIntegration.test.js
└── main.test.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .babelrc.js
================================================
module.exports = {
presets : [[
"@babel/preset-env", {
loose : true,
useBuiltIns : "entry",
targets : {
node : "6.11" // Minimum supported version
}
}
]],
plugins : [
["@babel/plugin-proposal-export-default-from", { loose: true }],
["@babel/plugin-proposal-export-namespace-from", { loose: true }],
["@babel/plugin-proposal-object-rest-spread", { loose: true }],
["add-module-exports", { loose: true }]
]
};
================================================
FILE: .editorconfig
================================================
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
max_line_length=80
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
================================================
FILE: .eslintrc.js
================================================
module.exports = {
parser : "babel-eslint",
extends : "airbnb-base",
rules : {
// Enforce the consistent use of double quotes
quotes : ["error", "double", { avoidEscape: true }],
// Allow bitwise operators
"no-bitwise" : "off",
// Allow the unary operators ++ and --
"no-plusplus" : "off",
// Require or disallow trailing commas
"comma-dangle": ["error", "only-multiline"],
// Disallow Reassignment of Function Parameters
"no-param-reassign" : ["error", { props: false }],
// Enforce consistent spacing between keys and values in object literal properties
"key-spacing" : ["error", {
singleLine : {
beforeColon : false,
afterColon : true
},
multiLine : {
beforeColon : true,
afterColon : true,
mode : "minimum"
}
}],
// Disallow multiple spaces
"no-multi-spaces" : ["error", { ignoreEOLComments: true }],
// Require or disallow padding within blocks
"padded-blocks": ["error", { classes: "always" }]
}
};
================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto
================================================
FILE: .gitignore
================================================
# Logs
*.log
npm-debug.log*
# Dependencies
node_modules
yarn.lock
# Coverage
/coverage
# Build
/lib
# OS - OSX
.DS_Store
# OS - Windows
Thumbs.db
ehthumbs.db
================================================
FILE: .nvmrc
================================================
v6.11.2
================================================
FILE: .travis.yml
================================================
language: node_js
sudo: false
node_js:
- "6"
- "8"
- "10"
before_install:
- if [[ `npm -v` != 6* ]]; then npm i -g npm@6; fi
install:
- npm install -g codecov
- npm run bootstrap
script:
- npm run style
- npm run coverage
after_success:
- codecov
================================================
FILE: CHANGELOG.md
================================================
# Changelog
See https://github.com/yvele/azure-function-express/releases
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
[Setup](#setup) |
[Commands](#command) |
[Unit Testing](#test) |
[Git Commit Guidelines](#commit)
## Setup
```sh
$ npm run bootstrap
```
## Unit Testing
### Running tests
```sh
$ npm run test
```
with coverage:
```sh
$ npm run coverage
```
### Writing tests
Test can be asserted with [Should.js](https://shouldjs.github.io) :
```js
test().should.be.type("string");
test().should.eql({ foo: "foo", bar: "bar" });
test().should.be.equal("foobar");
```
```js
import should from "should";
should.throws(() => {
throw new ArgumentError();
}, /ArgumentError/);
```
```js
it("Should fail", () => {
return testAsync().should.be.rejectedWith("Error message");
});
```
```js
import should from "should";
should.equal(test(), null);
should("foobar" == "foobar").be.ok;
```
## Commands
All commands should be run at the root path of the project.
| Command | Description |
|------------------------------|-------------------|
| `$ npm run bootstrap` | Setup the project for development
| `$ npm run build` | Build (with babel)
| `$ npm run clean` | Delete all temporary files (NPM, build, etc.)
| `$ npm run clean:build` | Delete build files (babel, etc.)
| `$ npm run clean:npm` | Delete NPM generated files (node_modules, logs, etc.)
| `$ npm run coverage` | Run unit tests with code coverage
| `$ npm run style` | Check code style
| `$ npm run test` | Run tests
| `$ npm run validate` | Check the code is valid by checking code style and running tests
## Git Commit Guidelines
Write meaningful and straightforward commit summaries.
```sh
# Bad
git commit assets -m 'change something' # ORLY? What change?
# Good
git commit assets -m 'style(css): Switch `reset.css` to `normalize.css`'
```
Avoid long commit summaries by limiting the maximum characters to `50`.
> Detailed descriptions should go on the commit message.
```sh
# Bad
git commit assets/javascripts -m 'Add `FIXME` note to dropdown module because it wasnt working on IE8'
# Good
git commit assets/javascripts -m 'style(dropdown): Add `FIXME` note to dropdown module'
```
Write commit summaries in the imperative, present tense.
```sh
# Bad
git commit scripts -m 'Fixed CI integration'
# Bad
git commit scripts -m 'Fixes CI integration'
# Bad
git commit scripts -m 'Fixing CI integration'
# Good
git commit scripts -m 'fix(ci): Fix CI integration'
```
Use proper english writing on commits.
> Because SCM is also code documentation.
```sh
# Bad (Everything in lower case, no proper punctuation and "whatever" really?)
git commit assets/stylesheets -m 'update clearfix or whatever'
# Bad (Why are you screaming?)
git commit assets/stylesheets -m 'UPDATE CLEARFIX'
# Good (Meaningful commit summary with proper orthography)
git commit assets/stylesheets -m 'fix(clearfix): Update clearfix implementation to use a more modern approach'
```
### Type
Must be one of the following:
| Prefix | Description |
|-------------|---------------|
| `feat` | A new feature
| `fix` | A bug fix
| `docs` | Documentation only changes
| `style` | Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
| `refactor ` | A code change that neither fixes a bug or adds a feature
| `test` | Adding missing tests
| `chore` | Changes to the build process or auxiliary tools and libraries such as documentation generation
### Scope
The scope could be anything specifying place of the commit change. For example `readme`,
`package.json`, `OptionManager`, `docs/Components`, etc...
### Subject
The subject contains succinct description of the change:
* Use the imperative, present tense: "change" not "changed" nor "changes"
* Capitalize first letter
* No dot (.) at the end
### Body
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
The body should include the motivation for the change and contrast this with previous behavior.
### About
Those rules have been inspired by AngularJS [contributing page](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md) and Netshoes [styleguide](https://github.com/netshoes/styleguide).
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# azure-function-express
> Allows Express usage with Azure Function
[](https://www.npmjs.com/package/azure-function-express)
[](https://github.com/Azure/azure-webjobs-sdk-script/issues/2036#issuecomment-336942961)


[](https://travis-ci.org/yvele/azure-function-express)
[](https://codecov.io/github/yvele/azure-function-express)
[](LICENSE)
## Description
[Connect](https://github.com/senchalabs/connect) your [Express](https://expressjs.com) application to an [Azure Function handler](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node), and make seamless usage of [all middlewares](http://expressjs.com/en/guide/using-middleware.html) you are already familiar with.
## Usage
In your `index.js`:
```js
const createHandler = require("azure-function-express").createHandler;
const express = require("express");
// Create express app as usual
const app = express();
app.get("/api/:foo/:bar", (req, res) => {
res.json({
foo : req.params.foo,
bar : req.params.bar
});
});
// Binds the express app to an Azure Function handler
module.exports = createHandler(app);
```
Make sure you are binding `req` and `res` in your `function.json`:
```json
{
"bindings": [{
"authLevel" : "anonymous",
"type" : "httpTrigger",
"direction" : "in",
"name" : "req",
"route" : "foo/{bar}/{id}"
}, {
"type" : "http",
"direction" : "out",
"name" : "res"
}]
}
```
To allow Express handles all HTTP routes itself you may set a glob star route in a single root `function.json`:
```json
{
"bindings": [{
"authLevel" : "anonymous",
"type" : "httpTrigger",
"direction" : "in",
"name" : "req",
"route" : "{*segments}"
}, {
"type" : "http",
"direction" : "out",
"name" : "res"
}]
}
```
Note that `segments` is not used and could be anything. See [Azure Function documentation](https://github.com/Azure/azure-webjobs-sdk-script/wiki/Http-Functions).
All examples [here](/examples/).
## Context
All native Azure Functions [context](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#context-object) properties, except `done`, are exposed through `req.context`.
As en example, you can [log](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#writing-trace-output-to-the-console) using:
```js
app.get("/api/hello-world", (req, res) => {
req.context.log({ hello: "world" });
...
});
```
## Runtime compatibility
Supported Node version are:
- Node 6.11.2 ([first node version supported by Azure Functions](https://github.com/Azure/azure-webjobs-sdk-script/issues/2036#issuecomment-336942961))
- Node 8 (LTS)
- Node 10
Azure Functions runtime v1 and v2 beta are both supported.
## License
[Apache 2.0](LICENSE) © Yves Merlicco
================================================
FILE: docs/azure-function.md
================================================
# Azure Function
## Documentation
- Documentation
- [Node Documentation](https://azure.microsoft.com/en-us/documentation/articles/functions-reference-node/)
- [WebJobs SDK Wiki](https://github.com/Azure/azure-webjobs-sdk-script/wiki)
- Changelog
- [Azure WebJobs SDK Releases](https://github.com/Azure/azure-webjobs-sdk-script/releases)
- [Azure WebJobs SDK Changelog](https://github.com/Azure/azure-webjobs-sdk/wiki/Release-Notes) (outdated!)
- [Data binding](https://azure.microsoft.com/en-us/documentation/articles/functions-bindings-http-webhook/)
## Response example
```js
context.res = { status: 202, body: "You successfully ordered more coffee!" };
```
## Context example
```js
context = {
invocationId : 'f0f6e586-0b79-4407-aa53-97919f45eba6',
log : [Function],
bindings: {
req: {
originalUrl: 'https://my-deployment-id.azurewebsites.net/api/get',
method: 'POST',
query: {},
headers: {
"connection" : "Keep-Alive",
"authorization" : "Bearer eyJhbGciOiJIUzI1NiIsIn...",
"host" : "my-deployment-id.azurewebsites.net",
"max-forwards" : "10",
"x-liveupgrade" : "1",
"x-arr-log-id" : "fe0ba896-00d0-4ce7-a790-c8978fcaa1fd",
"disguised-host" : "my-deployment-id.azurewebsites.net",
"x-site-deployment-id" : "my-deployment-id",
"was-default-hostname" : "my-deployment-id.azurewebsites.net",
"x-original-url" : "/api/get",
"x-forwarded-for" : "92.103.167.115:57996",
"x-arr-ssl" : "2048|256|C=US, S=Washington, L=Redmond, O=Microsoft Corporation, OU=Microsoft IT, CN=Microsoft IT SSL SHA2|CN=*.azurewebsites.net",
},
// form-data
body: "------WebKitFormBoundaryUPAtNZMGi7yHMoIX\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nb\r\n------WebKitFormBoundaryUPAtNZMGi7yHMoIX\r\nContent-Disposition: form-data; name=\"aa\"\r\n\r\nbb\r\n------WebKitFormBoundaryUPAtNZMGi7yHMoIX--\r\n",
rawBody: "------WebKitFormBoundaryUPAtNZMGi7yHMoIX\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nb\r\n------WebKitFormBoundaryUPAtNZMGi7yHMoIX\r\nContent-Disposition: form-data; name=\"aa\"\r\n\r\nbb\r\n------WebKitFormBoundaryUPAtNZMGi7yHMoIX--\r\n",
// x-www-form-urlencoded
body: "foo=bar&fou=barre",
rawBody: "foo=bar&fou=barre",
// raw --> application/json
"body": {
"foo": "bar",
"fou": "barre"
},
"rawBody": "{\n \"foo\": \"bar\",\n \"fou\": \"barre\"\n \n}",
}
},
bind: [Function],
bindingData: {
req: 'Method: POST, RequestUri: \'https://my-deployment-id.azurewebsites.net/api/get\', Version: 1.1, Content: System.Web.Http.WebHost.HttpControllerHandler+LazyStreamContent, Headers:\r\n{\r\n Connection: Keep-Alive\r\n Accept: application/json\r\n Accept: */*\r\n Accept-Encoding: gzip\r\n Accept-Encoding: deflate\r\n Accept-Encoding: br\r\n Accept-Language: fr\r\n Accept-Language: en-US; q=0.8\r\n Accept-Language: en; q=0.6\r\n Host: my-deployment-id.azurewebsites.net\r\n Max-Forwards: 10\r\n Referer: https://functions.azure.com/?trustedAuthority=https://portal.azure.com/\r\n User-Agent: Mozilla/5.0\r\n User-Agent: (Macintosh; Intel Mac OS X 10_11_6)\r\n User-Agent: AppleWebKit/537.36\r\n User-Agent: (KHTML, like Gecko)\r\n User-Agent: Chrome/52.0.2743.116\r\n User-Agent: Safari/537.36\r\n x-functions-key: G/6oEOahmJgI5Y1jfstIEpd1ygWwvERuylzEOnvUTUapJUsCYoEAyQ==\r\n Origin: https://functions.azure.com\r\n X-LiveUpgrade: 1\r\n X-ARR-LOG-ID: 865e04b5-923e-496a-a759-b0b36ab5b99b\r\n DISGUISED-HOST: my-deployment-id.azurewebsites.net\r\n X-SITE-DEPLOYMENT-ID: my-deployment-id\r\n WAS-DEFAULT-HOSTNAME: my-deployment-id.azurewebsites.net\r\n X-Original-URL: /api/get\r\n X-Forwarded-For: 92.103.167.115:58342\r\n X-ARR-SSL: 2048|256|C=US, S=Washington, L=Redmond, O=Microsoft Corporation, OU=Microsoft IT, CN=Microsoft IT SSL SHA2|CN=*.azurewebsites.net\r\n Content-Length: 0\r\n Content-Type: plain/text\r\n}',
InvocationId: 'f0f6e586-0b79-4407-aa53-97919f45eba6'
},
done : [Function],
res : {}
}
```
================================================
FILE: examples/all-routes/function.json
================================================
{
"disabled" : false,
"bindings" : [{
"authLevel" : "anonymous",
"type" : "httpTrigger",
"direction" : "in",
"name" : "req",
"route" : "{*segments}"
}, {
"type" : "http",
"direction" : "out",
"name" : "res"
}]
}
================================================
FILE: examples/all-routes/index.js
================================================
const createAzureFunctionHandler = require("azure-function-express").createAzureFunctionHandler;
const express = require("express");
// Create express app as usual
const app = express();
app.get("/api/:foo", (req, res) => res.json({ foo: req.params.foo }));
app.get("/api/:foo/:bar", (req, res) => res.json({ foo: req.params.foo, bar: req.params.bar }));
// Binds the express app to an Azure Function handler
module.exports = createAzureFunctionHandler(app);
================================================
FILE: examples/basic/function.json
================================================
{
"bindings": [{
"authLevel" : "anonymous",
"type" : "httpTrigger",
"direction" : "in",
"name" : "req",
"route" : "foo/{bar}/{id}"
}, {
"type" : "http",
"direction" : "out",
"name" : "res"
}]
}
================================================
FILE: examples/basic/index.js
================================================
const createAzureFunctionHandler = require("azure-function-express").createAzureFunctionHandler;
const express = require("express");
// Create express app as usual
const app = express();
app.get("/api/:foo/:bar", (req, res) => {
res.json({
foo : req.params.foo,
bar : req.params.bar
});
});
// Binds the express app to an Azure Function handler
module.exports = createAzureFunctionHandler(app);
================================================
FILE: examples/basic-module/function.json
================================================
{
"bindings": [{
"authLevel" : "anonymous",
"type" : "httpTrigger",
"direction" : "in",
"name" : "req",
"route" : "foo/{bar}/{id}"
}, {
"type" : "http",
"direction" : "out",
"name" : "res"
}]
}
================================================
FILE: examples/basic-module/index.js
================================================
import { createAzureFunctionHandler } from "azure-function-express";
import express from "express";
// Create express app as usual
const app = express();
app.get("/api/:foo/:bar", (req, res) => {
res.json({
foo : req.params.foo,
bar : req.params.bar
});
});
// Binds the express app to an Azure Function handler
export default createAzureFunctionHandler(app);
================================================
FILE: package.json
================================================
{
"name": "azure-function-express",
"version": "2.0.0",
"sideEffects": false,
"description": "Allows Express usage with Azure Function",
"keywords": [
"azure function",
"express",
"connect",
"azure",
"koa"
],
"homepage": "https://github.com/yvele/azure-function-express",
"bugs": {
"url": "https://github.com/yvele/azure-function-express/issues"
},
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/yvele/azure-function-express"
},
"files": [
"lib/"
],
"main": "lib/index.js",
"author": {
"name": "Merlicco Yves",
"email": "merlicco@gmail.com"
},
"contributors": [
"Yves Merlicco "
],
"scripts": {
"bootstrap": "npm install",
"build": "rm -rf lib && babel src --out-dir lib",
"clean": "rm -rf lib coverage node_modules",
"clean:build": "rm -rf lib",
"clean:npm": "rm -rf node_modules",
"coverage": "jest --coverage",
"publish": "npm run validate && npm run build && npm publish",
"style": "eslint src/**",
"test": "jest",
"validate": "npm run style && npm run coverage"
},
"engines": {
"node": ">=6.11.2 <11",
"npm": ">=6"
},
"devDependencies": {
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.0",
"@babel/plugin-proposal-export-default-from": "^7.0.0",
"@babel/plugin-proposal-export-namespace-from": "^7.0.0",
"@babel/plugin-proposal-object-rest-spread": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/register": "^7.0.0",
"babel-core": "^7.0.0-bridge.0",
"babel-eslint": "^9.0.0",
"babel-plugin-add-module-exports": "^0.2.1",
"eslint": "^5.5.0",
"eslint-config-airbnb-base": "^13.1.0",
"eslint-plugin-import": "^2.14.0",
"express": "^4.16.3",
"jest": "^23.5.0"
}
}
================================================
FILE: src/ExpressAdapter.js
================================================
import EventEmitter from "events";
import OutgoingMessage from "./OutgoingMessage";
import IncomingMessage from "./IncomingMessage";
/**
* @param {Object} context Azure Function native context object
* @throws {Error}
* @private
*/
function assertContext(context) {
if (!context) {
throw new Error("context is null or undefined");
}
if (!context.bindings) {
throw new Error("context.bindings is null or undefined");
}
if (!context.bindings.req) {
throw new Error("context.bindings.req is null or undefined");
}
if (!context.bindings.req.originalUrl) {
throw new Error("context.bindings.req.originalUrl is null or undefined");
}
}
/**
* Express adapter allowing to handle Azure Function requests by wrapping in request events.
*
* @class
* @fires request
*/
export default class ExpressAdapter extends EventEmitter {
/**
* @param {Object=} requestListener Request listener (typically an express/connect instance)
*/
constructor(requestListener) {
super();
if (requestListener !== undefined) {
this.addRequestListener(requestListener);
}
}
/**
* Adds a request listener (typically an express/connect instance).
*
* @param {Object} requestListener Request listener (typically an express/connect instance)
*/
addRequestListener(requestListener) {
this.addListener("request", requestListener);
}
/**
* Handles Azure Function requests.
*
* @param {Object} context Azure context object for a single request
*/
handleAzureFunctionRequest(context) {
assertContext(context);
// 1. Context basic initialization
context.res = context.res || {};
// 2. Wrapping
const req = new IncomingMessage(context);
const res = new OutgoingMessage(context);
// 3. Synchronously calls each of the listeners registered for the event
this.emit("request", req, res);
}
/**
* Create function ready to be exposed to Azure Function for request handling.
*
* @returns {function(context: Object)} Azure Function handle
*/
createAzureFunctionHandler() {
return this.handleAzureFunctionRequest.bind(this);
}
}
================================================
FILE: src/IncomingMessage.js
================================================
/* eslint-disable no-underscore-dangle */
import EventEmitter from "events";
const NOOP = () => {};
function removePortFromAddress(address) {
return address
? address.replace(/:[0-9]*$/, "")
: address;
}
/**
* Create a fake connection object
*
* @param {Object} context Raw Azure context object for a single HTTP request
* @returns {object} Connection object
*/
function createConnectionObject(context) {
const { req } = context.bindings;
const xForwardedFor = req.headers ? req.headers["x-forwarded-for"] : undefined;
return {
encrypted : req.originalUrl && req.originalUrl.toLowerCase().startsWith("https"),
remoteAddress : removePortFromAddress(xForwardedFor)
};
}
/**
* Copy usefull context properties from the native context provided by the Azure Function engine
*
* See:
* - https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#context-object
* - https://github.com/christopheranderson/azure-functions-typescript/blob/master/src/context.d.ts
*
* @param {Object} context Raw Azure context object for a single HTTP request
* @returns {Object} Filtered context
*/
function sanitizeContext(context) {
const sanitizedContext = {
...context,
log : context.log.bind(context)
};
// We don't want the developper to mess up express flow
// See https://github.com/yvele/azure-function-express/pull/12#issuecomment-336733540
delete sanitizedContext.done;
return sanitizedContext;
}
/**
* Request object wrapper
*
* @private
*/
export default class IncomingMessage extends EventEmitter {
/**
* Note: IncomingMessage assumes that all HTTP in is binded to "req" property
*
* @param {Object} context Sanitized Azure context object for a single HTTP request
*/
constructor(context) {
super();
Object.assign(this, context.bindings.req); // Inherit
this.url = this.originalUrl;
this.headers = this.headers || {}; // Should always have a headers object
this._readableState = { pipesCount: 0 }; // To make unpipe happy
this.resume = NOOP;
this.socket = { destroy: NOOP };
this.connection = createConnectionObject(context);
this.context = sanitizeContext(context); // Specific to Azure Function
}
}
================================================
FILE: src/OutgoingMessage.js
================================================
/* eslint-disable no-magic-numbers, no-underscore-dangle */
import { OutgoingMessage as NativeOutgoingMessage } from "http";
import statusCodes from "./statusCodes";
/**
* @param {Object|string|Buffer} body Express/connect body object
* @param {string} encoding
* @returns {Object|string} Azure Function body
*/
function convertToBody(body, encoding) {
// This may be removed on Azure Function native support for Buffer
// https://github.com/Azure/azure-webjobs-sdk-script/issues/814
// https://github.com/Azure/azure-webjobs-sdk-script/pull/781
return Buffer.isBuffer(body)
? body.toString(encoding)
: body;
}
/**
* @param {Object} context Azure Function context
* @param {string|Buffer} data
* @param {string} encoding
* @this {OutgoingMessage}
*/
function end(context, data, encoding) {
// 1. Write head
this.writeHead(this.statusCode); // Make jshttp/on-headers able to trigger
// 2. Return raw body to Azure Function runtime
context.res.body = convertToBody(data, encoding);
context.res.isRaw = true;
context.done();
}
/**
* https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers
* Original implementation: https://github.com/nodejs/node/blob/v6.x/lib/_http_server.js#L160
*
* @param {Object} context Azure Function context
* @param {number} statusCode
* @param {string} statusMessage
* @param {Object} headers
* @this {OutgoingMessage}
*/
function writeHead(context, statusCode, statusMessage, headers) {
// 1. Status code
statusCode |= 0; // eslint-disable-line no-param-reassign
if (statusCode < 100 || statusCode > 999) {
throw new RangeError(`Invalid status code: ${statusCode}`);
}
// 2. Status message
if (typeof statusMessage === "string") {
this.statusMessage = statusMessage;
} else {
this.statusMessage = statusCodes[statusCode] || "unknown";
}
// 3. Headers
if (typeof statusMessage === "object" && typeof headers === "undefined") {
headers = statusMessage; // eslint-disable-line no-param-reassign
}
if (this._headers) {
// Slow-case: when progressive API and header fields are passed.
if (headers) {
const keys = Object.keys(headers);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
if (k) {
this.setHeader(k, headers[k]);
}
}
}
// only progressive api is used
headers = this._renderHeaders(); // eslint-disable-line no-param-reassign
}
// 4. Sets everything
context.res.status = statusCode;
// In order to uniformize node 6 behaviour with node 8 and 10,
// we want to never have undefined headers, but instead empty object
context.res.headers = headers || {};
}
/**
* OutgoingMessage mock based on https://github.com/nodejs/node/blob/v6.x
*
* Note: This implementation is only meant to be working with Node.js v6.x
*
* @private
*/
export default class OutgoingMessage extends NativeOutgoingMessage {
/**
* Original implementation: https://github.com/nodejs/node/blob/v6.x/lib/_http_outgoing.js#L48
*/
constructor(context) {
super();
this._headers = null;
this._headerNames = {};
this._removedHeader = {};
this._hasBody = true;
// Those methods cannot be prototyped because express explicitelly overrides __proto__
// See https://github.com/expressjs/express/blob/master/lib/middleware/init.js#L29
this.writeHead = writeHead.bind(this, context);
this.end = end.bind(this, context);
}
}
================================================
FILE: src/createAzureFunctionHandler.js
================================================
import ExpressAdapter from "./ExpressAdapter";
/**
* Creates a function ready to be exposed to Azure Function for request handling.
*
* @param {Object} requestListener Request listener (typically an express/connect instance)
* @returns {function(context: Object)} Azure Function handle
*/
export default function createAzureFunctionHandler(requestListener) {
const adapter = new ExpressAdapter(requestListener);
return adapter.createAzureFunctionHandler();
}
================================================
FILE: src/index.js
================================================
import createAzureFunctionHandler from "./createAzureFunctionHandler";
export ExpressAdapter from "./ExpressAdapter";
export { createAzureFunctionHandler, createAzureFunctionHandler as createHandler };
================================================
FILE: src/statusCodes.js
================================================
export default {
100 : "Continue",
101 : "Switching Protocols",
102 : "Processing", // RFC 2518, obsoleted by RFC 4918
200 : "OK",
201 : "Created",
202 : "Accepted",
203 : "Non-Authoritative Information",
204 : "No Content",
205 : "Reset Content",
206 : "Partial Content",
207 : "Multi-Status", // RFC 4918
208 : "Already Reported",
226 : "IM Used",
300 : "Multiple Choices",
301 : "Moved Permanently",
302 : "Found",
303 : "See Other",
304 : "Not Modified",
305 : "Use Proxy",
307 : "Temporary Redirect",
308 : "Permanent Redirect", // RFC 7238
400 : "Bad Request",
401 : "Unauthorized",
402 : "Payment Required",
403 : "Forbidden",
404 : "Not Found",
405 : "Method Not Allowed",
406 : "Not Acceptable",
407 : "Proxy Authentication Required",
408 : "Request Timeout",
409 : "Conflict",
410 : "Gone",
411 : "Length Required",
412 : "Precondition Failed",
413 : "Payload Too Large",
414 : "URI Too Long",
415 : "Unsupported Media Type",
416 : "Range Not Satisfiable",
417 : "Expectation Failed",
418 : "I\"m a teapot", // RFC 2324
421 : "Misdirected Request",
422 : "Unprocessable Entity", // RFC 4918
423 : "Locked", // RFC 4918
424 : "Failed Dependency", // RFC 4918
425 : "Unordered Collection", // RFC 4918
426 : "Upgrade Required", // RFC 2817
428 : "Precondition Required", // RFC 6585
429 : "Too Many Requests", // RFC 6585
431 : "Request Header Fields Too Large", // RFC 6585
451 : "Unavailable For Legal Reasons",
500 : "Internal Server Error",
501 : "Not Implemented",
502 : "Bad Gateway",
503 : "Service Unavailable",
504 : "Gateway Timeout",
505 : "HTTP Version Not Supported",
506 : "Variant Also Negotiates", // RFC 2295
507 : "Insufficient Storage", // RFC 4918
508 : "Loop Detected",
509 : "Bandwidth Limit Exceeded",
510 : "Not Extended", // RFC 2774
511 : "Network Authentication Required" // RFC 6585
};
================================================
FILE: test/ExpressAdapter.test.js
================================================
import { ExpressAdapter } from "../src";
const NOOP = () => {};
describe("ExpressAdapter", () => {
it("Should work", done => {
let listenerCalled = false;
const adapter = new ExpressAdapter((req, res) => {
listenerCalled = true;
expect(req.url).toBe("http://foo.com/bar");
res.statusCode = 200;
res.end("body", "utf8");
});
const context = {
log : NOOP,
bindings : { req: { originalUrl: "http://foo.com/bar" } },
done : () => {
expect(listenerCalled).toBe(true);
// Response that will be sent to Azure Function runtime
expect(context.res).toEqual({
body : "body",
headers : {},
isRaw : true,
status : 200
});
done();
}
};
const handler = adapter.createAzureFunctionHandler();
handler(context);
});
it("Should work with a buffer", done => {
let listenerCalled = false;
const adapter = new ExpressAdapter((req, res) => {
listenerCalled = true;
expect(req.url).toBe("http://foo.com/bar");
res.statusCode = 200;
res.end(Buffer.from("body", "utf8"), "utf8");
});
const context = {
log : NOOP,
bindings : { req: { originalUrl: "http://foo.com/bar" } },
done : () => {
expect(listenerCalled).toBe(true);
// Response that will be sent to Azure Function runtime
expect(context.res).toEqual({
body : "body",
headers : {},
isRaw : true,
status : 200
});
done();
}
};
const handler = adapter.createAzureFunctionHandler();
handler(context);
});
describe("handleAzureFunctionRequest", () => {
it("Should throws with no context", () => {
const adapter = new ExpressAdapter();
expect(() => {
adapter.handleAzureFunctionRequest();
}).toThrowError(/^context is null or undefined/);
});
it("Should throws with a context with no bindings", () => {
const adapter = new ExpressAdapter();
expect(() => {
adapter.handleAzureFunctionRequest({});
}).toThrowError(/^context.bindings is null or undefined/);
});
it("Should throws with a context with no req binding", () => {
const adapter = new ExpressAdapter();
expect(() => {
adapter.handleAzureFunctionRequest({ bindings: {} });
}).toThrowError(/^context.bindings.req is null or undefined/);
});
it("Should throws with a context with a req binding having no originalUrl", () => {
const adapter = new ExpressAdapter();
expect(() => {
adapter.handleAzureFunctionRequest({ bindings: { req: {} } });
}).toThrowError(/^context.bindings.req.originalUrl is null or undefined/);
});
});
});
================================================
FILE: test/IncomingMessage.test.js
================================================
import IncomingMessage from "../src/IncomingMessage";
describe("IncomingMessage", () => {
it("Should work", () => {
const context = {
bindings : {
req : {
originalUrl : "https://foo.com/bar",
headers : { "x-forwarded-for": "192.168.0.1:57996" }
}
},
log : () => {}
};
const req = new IncomingMessage(context);
req.resume();
req.socket.destroy();
expect(req).toMatchObject({
url : "https://foo.com/bar",
connection : {
encrypted : true,
remoteAddress : "192.168.0.1"
}
});
});
it("Should work with no headers", () => {
const context = {
bindings : {
req : {
originalUrl : "http://foo.com/bar"
}
},
log : () => {}
};
const req = new IncomingMessage(context);
req.resume();
req.socket.destroy();
expect(req).toMatchObject({
url : "http://foo.com/bar",
connection : {
encrypted : false,
remoteAddress : undefined
}
});
});
it("Should work with a full native context object", () => {
const context = {
invocationId : "f0f6e586-0b79-4407-aa53-97919f45eba5",
bindingData : { foo: "bar" },
bindings : {
req : {
originalUrl : "http://foo.com/bar"
}
},
log : () => {},
done : () => {}
};
const req = new IncomingMessage(context);
req.resume();
req.socket.destroy();
expect(req).toMatchObject({
url : "http://foo.com/bar",
connection : {
encrypted : false,
remoteAddress : undefined
}
});
expect(req.context).toBeDefined();
expect(req.context).not.toBe(context);
expect(req.context.invocationId).toBe(context.invocationId);
expect(req.context.bindingData).toBe(context.bindingData);
expect(req.context.bindings).toBe(context.bindings);
expect(req.context.log).not.toBe(context.log);
expect(req.context.log).toBeInstanceOf(Function);
expect(req.context.done).toBeUndefined(); // We don't want to pass done
});
});
================================================
FILE: test/OutgoingMessage.test.js
================================================
import OutgoingMessage from "../src/OutgoingMessage";
describe("OutgoingMessage", () => {
describe("writeHead", () => {
it("Should throws with an invalid status code", () => {
const res = new OutgoingMessage();
expect(() => {
res.writeHead(1);
}).toThrow(/^Invalid status code: 1/);
});
it("Should handle unknown status codes", () => {
const context = { res: {} };
const res = new OutgoingMessage(context);
res.writeHead(998);
expect(res.statusMessage).toBe("unknown");
expect(context.res.status).toBe(998);
});
it("Should work with headers", () => {
const context = { res: {} };
const res = new OutgoingMessage(context);
res.writeHead(200, null, { foo: "bar" });
expect(res.statusMessage).toBe("OK");
expect(context.res.status).toBe(200);
expect(context.res.headers).toEqual({ foo: "bar" });
});
it("Should work with headers with previous headers", () => {
const context = { res: {} };
const res = new OutgoingMessage(context);
res._headers = { previous: "previous" };
res._renderHeaders = () => res._headers;
res.writeHead(200, null, { foo: "bar" });
expect(res.statusMessage).toBe("OK");
expect(context.res.status).toBe(200);
expect(context.res.headers).toEqual({ foo: "bar", previous: "previous" });
});
it("Should work with a status message", () => {
const context = { res: {} };
const res = new OutgoingMessage(context);
res.writeHead(200, "baz", { foo: "bar" });
expect(res.statusMessage).toBe("baz");
expect(context.res.status).toBe(200);
expect(context.res.headers).toEqual({ foo: "bar" });
});
it("Should work with a headers as second parameter if no status message is given", () => {
const context = { res: {} };
const res = new OutgoingMessage(context);
res.writeHead(200, { foo: "bar" });
expect(res.statusMessage).toBe("OK");
expect(context.res.status).toBe(200);
expect(context.res.headers).toEqual({ foo: "bar" });
});
});
});
================================================
FILE: test/expressIntegration.test.js
================================================
import express from "express";
import { createAzureFunctionHandler } from "../src";
describe("express integration", () => {
it("should work with x-powered-by", done => {
// 1. Create express app
const app = express();
app.get("/api/:foo/:bar", (req, res) => {
res.set("Cache-Control", "max-age=600");
res.json({ foo: req.params.foo, bar: req.params.bar });
});
// 2. Create handle
const handle = createAzureFunctionHandler(app);
// 3. Mock Azure Function context
var context = {
bindings : { req: { method: "GET", originalUrl: "https://lol.com/api/foo/bar" } },
log : () => { throw new Error("Log should not be called"); },
done : (error) => {
expect(error).toBeUndefined();
expect(context.res.status).toBe(200);
expect(context.res.body).toBe('{"foo":"foo","bar":"bar"}');
expect(context.res.headers).toEqual({
"X-Powered-By" : "Express",
"Cache-Control" : "max-age=600",
"Content-Type" : "application/json; charset=utf-8",
"Content-Length" : "25",
ETag : 'W/"19-0CKEGOfZ5AYCM4LPaa4gzWL6olU"'
});
done();
}
};
// 4. Call the handle with the mockup
handle(context, context.req);
});
it("should work without x-powered-by", done => {
// 1. Create express app
const app = express();
app.disable("x-powered-by");
app.get("/api/:foo/:bar", (req, res) => {
res.json({ foo: req.params.foo, bar: req.params.bar });
});
// 2. Create handle
const handle = createAzureFunctionHandler(app);
// 3. Mock Azure Function context
var context = {
bindings : { req: { method: "GET", originalUrl: "https://lol.com/api/foo/bar" } },
log : () => { throw new Error("Log should not be called"); },
done : (error) => {
expect(error).toBeUndefined();
expect(context.res.status).toBe(200);
expect(context.res.body).toBe('{"foo":"foo","bar":"bar"}');
expect(context.res.headers).toEqual({
"Content-Type" : "application/json; charset=utf-8",
"Content-Length" : "25",
ETag : 'W/"19-0CKEGOfZ5AYCM4LPaa4gzWL6olU"'
});
done();
}
};
// 4. Call the handle with the mockup
handle(context, context.req);
});
});
================================================
FILE: test/main.test.js
================================================
import { createAzureFunctionHandler, createHandler } from "../src";
const NOOP = () => {};
describe("main", () => {
it("createAzureFunctionHandler should work", () => {
expect(createAzureFunctionHandler(NOOP)).toBeInstanceOf(Function);
});
it("createHandler should work", () => {
expect(createHandler(NOOP)).toBeInstanceOf(Function);
});
});