Repository: nestjs/azure-func-http
Branch: master
Commit: ed87cce6b3cc
Files: 49
Total size: 51.6 KB
Directory structure:
gitextract_sh6w41v4/
├── .circleci/
│ └── config.yml
├── .commitlintrc.json
├── .eslintrc.js
├── .github/
│ ├── ISSUE_TEMPLATE.md
│ └── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── .npmignore
├── .prettierignore
├── .prettierrc
├── .release-it.json
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── index.d.ts
├── index.js
├── index.ts
├── jest.json
├── lib/
│ ├── adapter/
│ │ ├── azure-adapter.ts
│ │ ├── azure-reply.ts
│ │ ├── azure-request.ts
│ │ └── index.ts
│ ├── azure-http.adapter.ts
│ ├── index.ts
│ └── router/
│ ├── azure-http.router.ts
│ └── index.ts
├── package.json
├── renovate.json
├── schematics/
│ ├── collection.json
│ └── install/
│ ├── files/
│ │ ├── project/
│ │ │ ├── .funcignore
│ │ │ ├── __project__/
│ │ │ │ ├── function.json
│ │ │ │ ├── index.ts
│ │ │ │ └── webpack.config.js
│ │ │ ├── __sourceRoot__/
│ │ │ │ └── main.azure.ts
│ │ │ ├── host.json
│ │ │ ├── local.settings.json
│ │ │ └── proxies.json
│ │ └── root/
│ │ ├── .funcignore
│ │ ├── __rootDir__/
│ │ │ └── main.azure.ts
│ │ ├── host.json
│ │ ├── local.settings.json
│ │ ├── main/
│ │ │ ├── function.json
│ │ │ └── index.ts
│ │ └── proxies.json
│ ├── index.test.ts
│ ├── index.ts
│ ├── schema.json
│ └── schema.ts
├── tsconfig.json
└── tsconfig.schematics.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .circleci/config.yml
================================================
version: 2
aliases:
- &restore-cache
restore_cache:
name: Restore Yarn Package Cache
keys:
- yarn-packages-{{ checksum "yarn.lock" }}
- &install-deps
run:
name: Install dependencies
command: yarn
- &build-packages
run:
name: Build
command: npm run build
jobs:
build:
working_directory: ~/nest
docker:
- image: cimg/node:20.3
steps:
- checkout
- restore_cache:
name: Restore Yarn Package Cache
keys:
- yarn-packages-{{ checksum "yarn.lock" }}
- run:
name: Install dependencies
command: yarn
- save_cache:
name: Save Yarn Package Cache
key: yarn-packages-{{ checksum "yarn.lock" }}
paths:
- ~/.cache/yarn
- run:
name: Build
command: npm run build
unit_tests:
working_directory: ~/nest
docker:
- image: cimg/node:20.3
steps:
- checkout
- restore_cache:
name: Restore Yarn Package Cache
keys:
- yarn-packages-{{ checksum "yarn.lock" }}
- run:
name: Install dependencies
command: yarn
- save_cache:
name: Save Yarn Package Cache
key: yarn-packages-{{ checksum "yarn.lock" }}
paths:
- ~/.cache/yarn
- run:
name: Tests
command: npm run test
workflows:
version: 2
build-and-test:
jobs:
- build
- unit_tests:
requires:
- build
================================================
FILE: .commitlintrc.json
================================================
{
"extends": ["@commitlint/config-angular"],
"rules": {
"subject-case": [
2,
"always",
["sentence-case", "start-case", "pascal-case", "upper-case", "lower-case"]
],
"type-enum": [
2,
"always",
[
"build",
"chore",
"ci",
"docs",
"feat",
"fix",
"perf",
"refactor",
"revert",
"style",
"test",
"sample"
]
]
}
}
================================================
FILE: .eslintrc.js
================================================
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module'
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier'
],
root: true,
env: {
node: true,
jest: true
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off'
}
};
================================================
FILE: .github/ISSUE_TEMPLATE.md
================================================
## I'm submitting a...
[ ] Regression
[ ] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
## Current behavior
## Expected behavior
## Minimal reproduction of the problem with instructions
## What is the motivation / use case for changing the behavior?
## Environment
Nest version: X.Y.Z
For Tooling issues:
- Node version: XX
- Platform:
Others:
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
## PR Checklist
Please check if your PR fulfills the following requirements:
- [ ] The commit message follows our guidelines: https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md
- [ ] Tests for the changes have been added (for bug fixes / features)
- [ ] Docs have been added / updated (for bug fixes / features)
## PR Type
What kind of change does this PR introduce?
- [ ] Bugfix
- [ ] Feature
- [ ] Code style update (formatting, local variables)
- [ ] Refactoring (no functional changes, no api changes)
- [ ] Build related changes
- [ ] CI related changes
- [ ] Other... Please describe:
## What is the current behavior?
Issue Number: N/A
## What is the new behavior?
## Does this PR introduce a breaking change?
- [ ] Yes
- [ ] No
## Other information
================================================
FILE: .gitignore
================================================
# dependencies
/node_modules
# IDE
/.idea
/.awcache
/.vscode
# misc
npm-debug.log
.DS_Store
# tests
/test
/coverage
/.nyc_output
# source
dist
# schematics
schematics/install/*.js
schematics/install/*.d.ts
schematics/install/express-engine/*.js
schematics/install/express-engine/*.d.ts
================================================
FILE: .npmignore
================================================
# source
lib
/index.ts
package-lock.json
tslint.json
.prettierrc
# schematics
schematics/install/*.ts
schematics/install/express-engine/*.ts
# misc
.DS_Store
================================================
FILE: .prettierignore
================================================
schematics/install/files/**/*.ts
================================================
FILE: .prettierrc
================================================
{
"trailingComma": "none",
"singleQuote": true
}
================================================
FILE: .release-it.json
================================================
{
"git": {
"commitMessage": "chore(): release v${version}"
},
"github": {
"release": true
}
}
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to Nest
We would love for you to contribute to Nest and help make it even better than it is
today! As a contributor, here are the guidelines we would like you to follow:
- [Code of Conduct](#coc)
- [Question or Problem?](#question)
- [Issues and Bugs](#issue)
- [Feature Requests](#feature)
- [Submission Guidelines](#submit)
- [Coding Rules](#rules)
- [Commit Message Guidelines](#commit)
## Got a Question or Problem?
**Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests.** You've got much better chances of getting your question answered on [Stack Overflow](https://stackoverflow.com/questions/tagged/nestjs) where the questions should be tagged with tag `nestjs`.
Stack Overflow is a much better place to ask questions since:
- questions and answers stay available for public viewing so your question / answer might help someone else
- Stack Overflow's voting system assures that the best answers are prominently visible.
To save your and our time, we will systematically close all issues that are requests for general support and redirect people to Stack Overflow.
If you would like to chat about the question in real-time, you can reach out via [our gitter channel][gitter].
## Found a Bug?
If you find a bug in the source code, you can help us by
[submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can
[submit a Pull Request](#submit-pr) with a fix.
## Missing a Feature?
You can *request* a new feature by [submitting an issue](#submit-issue) to our GitHub
Repository. If you would like to *implement* a new feature, please submit an issue with
a proposal for your work first, to be sure that we can use it.
Please consider what kind of change it is:
* For a **Major Feature**, first open an issue and outline your proposal so that it can be
discussed. This will also allow us to better coordinate our efforts, prevent duplication of work,
and help you to craft the change so that it is successfully accepted into the project. For your issue name, please prefix your proposal with `[discussion]`, for example "[discussion]: your feature idea".
* **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
## Submission Guidelines
### Submitting an Issue
Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.
We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs we will systematically ask you to provide a minimal reproduction scenario using a repository or [Gist](https://gist.github.com/). Having a live, reproducible scenario gives us wealth of important information without going back & forth to you with additional questions like:
- version of NestJS used
- 3rd-party libraries and their versions
- and most importantly - a use-case that fails
Unfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that don't have enough info to be reproduced.
You can file new issues by filling out our [new issue form](https://github.com/nestjs/nest/issues/new).
### Submitting a Pull Request (PR)
Before you submit your Pull Request (PR) consider the following guidelines:
1. Search [GitHub](https://github.com/nestjs/nest/pulls) for an open or closed PR
that relates to your submission. You don't want to duplicate effort.
1. Fork the nestjs/nest repo.
1. Make your changes in a new git branch:
```shell
git checkout -b my-fix-branch master
```
1. Create your patch, **including appropriate test cases**.
1. Follow our [Coding Rules](#rules).
1. Run the full Nest test suite, as described in the [developer documentation][dev-doc],
and ensure that all tests pass.
1. Commit your changes using a descriptive commit message that follows our
[commit message conventions](#commit). Adherence to these conventions
is necessary because release notes are automatically generated from these messages.
```shell
git commit -a
```
Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
1. Push your branch to GitHub:
```shell
git push origin my-fix-branch
```
1. In GitHub, send a pull request to `nestjs:master`.
* If we suggest changes then:
* Make the required updates.
* Re-run the Nest test suites to ensure tests are still passing.
* Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
```shell
git rebase master -i
git push -f
```
That's it! Thank you for your contribution!
#### After your pull request is merged
After your pull request is merged, you can safely delete your branch and pull the changes
from the main (upstream) repository:
* Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows:
```shell
git push origin --delete my-fix-branch
```
* Check out the master branch:
```shell
git checkout master -f
```
* Delete the local branch:
```shell
git branch -D my-fix-branch
```
* Update your master with the latest upstream version:
```shell
git pull --ff upstream master
```
## Coding Rules
To ensure consistency throughout the source code, keep these rules in mind as you are working:
* All features or bug fixes **must be tested** by one or more specs (unit-tests).
* We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at
**100 characters**. An automated formatter is available, see
[DEVELOPER.md](docs/DEVELOPER.md#clang-format).
## Commit Message Guidelines
We have very precise rules over how our git commit messages can be formatted. This leads to **more
readable messages** that are easy to follow when looking through the **project history**. But also,
we use the git commit messages to **generate the Nest change log**.
### Commit Message Format
Each commit message consists of a **header**, a **body** and a **footer**. The header has a special
format that includes a **type**, a **scope** and a **subject**:
```
():
```
The **header** is mandatory and the **scope** of the header is optional.
Any line of the commit message cannot be longer 100 characters! This allows the message to be easier
to read on GitHub as well as in various git tools.
Footer should contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages/) if any.
Samples: (even more [samples](https://github.com/nestjs/nest/commits/master))
```
docs(changelog) update change log to beta.5
```
```
fix(@nestjs/core) need to depend on latest rxjs and zone.js
The version in our package.json gets copied to the one we publish, and users need the latest of these.
```
### Revert
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body it should say: `This reverts commit .`, where the hash is the SHA of the commit being reverted.
### Type
Must be one of the following:
* **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
* **chore**: Updating tasks etc; no production code change
* **ci**: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
* **docs**: Documentation only changes
* **feat**: A new feature
* **fix**: A bug fix
* **perf**: A code change that improves performance
* **refactor**: A code change that neither fixes a bug nor adds a feature
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
* **test**: Adding missing tests or correcting existing tests
### Subject
The subject contains succinct description of the change:
* use the imperative, present tense: "change" not "changed" nor "changes"
* don't 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.
### Footer
The footer should contain any information about **Breaking Changes** and is also the place to
reference GitHub issues that this commit **Closes**.
**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.
A detailed explanation can be found in this [document][commit-message-format].
[commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#
[corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html
[dev-doc]: https://github.com/nestjs/nest/blob/master/docs/DEVELOPER.md
[github]: https://github.com/nestjs/nest
[gitter]: https://gitter.im/nestjs/nest
[individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html
[js-style-guide]: https://google.github.io/styleguide/jsguide.html
[jsfiddle]: http://jsfiddle.net
[plunker]: http://plnkr.co/edit
[runnable]: http://runnable.com
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2017-2021 Kamil Mysliwiec
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
[travis-image]: https://api.travis-ci.org/nestjs/nest.svg?branch=master
[travis-url]: https://travis-ci.org/nestjs/nest
[linux-image]: https://img.shields.io/travis/nestjs/nest/master.svg?label=linux
[linux-url]: https://travis-ci.org/nestjs/nest
A progressive Node.js framework for building efficient and scalable server-side applications.
## Description
[Azure Functions](https://code.visualstudio.com/tutorials/functions-extension/getting-started) HTTP module for [Nest](https://github.com/nestjs/nest).
## Installation
Using the Nest CLI:
```bash
$ nest add @nestjs/azure-func-http
```
Example output:
```bash
✔ Installation in progress... ☕
CREATE /.funcignore (66 bytes)
CREATE /host.json (23 bytes)
CREATE /local.settings.json (116 bytes)
CREATE /proxies.json (72 bytes)
CREATE /main/function.json (294 bytes)
CREATE /main/index.ts (287 bytes)
CREATE /main/sample.dat (23 bytes)
CREATE /src/main.azure.ts (321 bytes)
UPDATE /package.json (1827 bytes)
```
## Tutorial
You can read more about this integration [here](https://trilon.io/blog/deploy-nestjs-azure-functions).
## Native routing
If you don't need the compatibility with `express` library, you can use a native routing instead:
```typescript
const app = await NestFactory.create(AppModule, new AzureHttpRouter());
```
`AzureHttpRouter` is exported from `@nestjs/azure-func-http`. Since `AzureHttpRouter` doesn't use `express` underneath, the routing itself is much faster.
## Additional options
You can pass additional flags to customize the post-install schematic. For example, if your base application directory is different than `src`, use `--rootDir` flag:
```bash
$ nest add @nestjs/azure-func-http --rootDir app
```
Other available flags:
- `rootModuleFileName` - the name of the root module file, default: `app.module`
- `rootModuleClassName` - the name of the root module class, default: `AppModule`
- `skipInstall` - skip installing dependencies, default: `false`
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).
================================================
FILE: index.d.ts
================================================
export * from './dist';
================================================
FILE: index.js
================================================
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
exports.__esModule = true;
__export(require("./dist"));
================================================
FILE: index.ts
================================================
export * from './dist';
================================================
FILE: jest.json
================================================
{
"moduleFileExtensions": ["js", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".(test|spec).ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "./coverage",
"verbose": true,
"bail": true,
"testPathIgnorePatterns": ["/node_modules/", "files"]
}
================================================
FILE: lib/adapter/azure-adapter.ts
================================================
import { AzureRequest } from './azure-request';
import { AzureReply } from './azure-reply';
export function createHandlerAdapter(handler) {
return context => {
context.res = context.res || {};
const req = new AzureRequest(context);
const res = new AzureReply(context);
handler(req, res);
};
}
================================================
FILE: lib/adapter/azure-reply.ts
================================================
import { OutgoingMessage } from 'http';
export class AzureReply extends OutgoingMessage {
private readonly _headerSent: boolean;
private readonly outputData: { data: any }[];
statusCode?: number;
constructor(context: Record) {
super();
// Avoid issues when data is streamed out
this._headerSent = true;
this.writeHead = this.writeHead.bind(this, context);
this.end = this.finish.bind(this, context);
}
writeHead(
context: Record,
statusCode: number,
statusMessage: string,
headers: Record
) {
if (statusCode) {
this.statusCode = statusCode;
}
if (headers) {
const keys = Object.keys(headers);
for (const key of keys) {
this.setHeader(key, headers[key]);
}
}
context.res.status = this.statusCode;
context.res.headers = this.getHeaders() || {};
}
finish(context: Record, body: Record | undefined) {
// If data was streamed out, get it back to body
if (body === undefined && this.outputData.length > 0) {
body = Buffer.concat(
this.outputData.map(o =>
Buffer.isBuffer(o.data) ? o.data : Buffer.from(o.data)
)
);
}
context.res.status = this.statusCode;
context.res.body = body;
context.done();
}
}
================================================
FILE: lib/adapter/azure-request.ts
================================================
import { Readable } from 'stream';
export class AzureRequest extends Readable {
readonly url: string;
readonly context: Record;
readonly originalUrl: string;
readonly headers: Record;
readonly body: any;
constructor(context: Record) {
super();
Object.assign(this, context.req);
this.context = context;
this.url = this.originalUrl;
this.headers = this.headers || {};
// Recreate original request stream from body
const body = Buffer.isBuffer(context.req.body)
? context.req.body
: context.req.rawBody;
if (body !== null && body !== undefined) {
this.push(body);
}
// Close the stream
this.push(null);
}
}
================================================
FILE: lib/adapter/index.ts
================================================
export * from './azure-adapter';
export * from './azure-reply';
export * from './azure-request';
================================================
FILE: lib/azure-http.adapter.ts
================================================
/* eslint-disable @typescript-eslint/ban-types */
import { Context, HttpRequest } from '@azure/functions';
import { HttpServer, INestApplication } from '@nestjs/common';
import { createHandlerAdapter } from './adapter/azure-adapter';
import { AzureHttpRouter } from './router';
let handler: Function;
export class AzureHttpAdapterStatic {
handle(
createApp: () => Promise,
context: Context,
req: HttpRequest
) {
if (handler) {
return handler(context, req);
}
this.createHandler(createApp).then((fn) => fn(context, req));
}
private async createHandler(
createApp: () => Promise<
Omit
>
) {
const app = await createApp();
const adapter = app.getHttpAdapter();
if (this.hasGetTypeMethod(adapter) && adapter.getType() === 'azure-http') {
return (adapter as any as AzureHttpRouter).handle.bind(adapter);
}
const instance = app.getHttpAdapter().getInstance();
handler = createHandlerAdapter(instance);
return handler;
}
private hasGetTypeMethod(
adapter: HttpServer
): adapter is HttpServer & { getType: Function } {
return !!(adapter as any).getType;
}
}
export const AzureHttpAdapter = new AzureHttpAdapterStatic();
================================================
FILE: lib/index.ts
================================================
export * from './azure-http.adapter';
export * from './router';
export * from './adapter';
================================================
FILE: lib/router/azure-http.router.ts
================================================
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-function */
import {
HttpStatus,
InternalServerErrorException,
NotImplementedException,
RequestMethod,
VersioningOptions
} from '@nestjs/common';
import { VersionValue } from '@nestjs/common/interfaces';
import { CorsOptions } from '@nestjs/common/interfaces/external/cors-options.interface';
import { AbstractHttpAdapter } from '@nestjs/core';
import { RouterMethodFactory } from '@nestjs/core/helpers/router-method-factory';
import * as cors from 'cors';
import TRouter from 'trouter';
import { AzureReply, AzureRequest } from '../adapter';
export class AzureHttpRouter extends AbstractHttpAdapter {
private readonly routerMethodFactory = new RouterMethodFactory();
constructor() {
super(new TRouter());
}
public handle(context: Record, request: any) {
const req = context.req;
const originalUrl = req.originalUrl as string;
const path = new URL(originalUrl).pathname;
const { params, handlers } = this.instance.find(req.method, path);
req.params = params;
if (handlers.length === 0) {
return this.handleNotFound(context, req.method, originalUrl);
}
const azureRequest = new AzureRequest(context);
const azureReply = new AzureReply(context);
const nextRoute = (i = 0) =>
handlers[i] &&
handlers[i](azureRequest, azureReply, () => nextRoute(i + 1));
nextRoute();
}
public handleNotFound(
context: Record,
method: string,
originalUrl: string
) {
context.res.status = HttpStatus.NOT_FOUND;
context.res.body = {
statusCode: HttpStatus.NOT_FOUND,
error: `Cannot ${method} ${originalUrl}`
};
context.done();
return;
}
public enableCors(options: CorsOptions) {
this.use(cors(options));
}
public reply(response: any, body: any, statusCode?: number) {
response.writeHead(statusCode);
response.end(body);
}
public status(response: any, statusCode: number) {
response.statusCode = statusCode;
}
public end(response: any, message?: string) {
return response.end(message);
}
public getHttpServer(): T {
return this.instance as T;
}
public getInstance(): T {
return this.instance as T;
}
public isHeadersSent(response: any): boolean {
return response.headersSent;
}
public setHeader(response: any, name: string, value: string) {
return response.setHeader(name, value);
}
public getRequestMethod(request: any): string {
return request.method;
}
public getRequestUrl(request: any): string {
return request.url;
}
public getRequestHostname(request: any): string {
return request.hostname;
}
public createMiddlewareFactory(
requestMethod: RequestMethod
): (path: string, callback: Function) => any {
return this.routerMethodFactory
.get(this.instance, requestMethod)
.bind(this.instance);
}
public getType(): string {
return 'azure-http';
}
public applyVersionFilter(
handler: Function,
version: VersionValue,
versioningOptions: VersioningOptions
) {
throw new NotImplementedException();
return (req, res, next) => {
return () => {};
};
}
public listen(port: any, ...args: any[]) {}
public render(response: any, view: string, options: any) {}
public redirect(response: any, statusCode: number, url: string) {}
public close() {}
public initHttpServer() {}
public useStaticAssets(options: any) {}
public setViewEngine(options: any) {}
public registerParserMiddleware() {}
public setNotFoundHandler(handler: Function) {}
public setErrorHandler(handler: Function) {}
}
================================================
FILE: lib/router/index.ts
================================================
export * from './azure-http.router';
================================================
FILE: package.json
================================================
{
"name": "@nestjs/azure-func-http",
"version": "0.10.0",
"description": "Nest - modern, fast, powerful node.js web framework (@azure-func-http)",
"author": "Kamil Mysliwiec",
"license": "MIT",
"scripts": {
"build": "npm run build:lib && npm run build:schematics",
"build:lib": "tsc -p tsconfig.json",
"build:schematics": "tsc -p tsconfig.schematics.json",
"lint": "eslint --ext ts --fix lib",
"format": "prettier --write \"lib/**/*.ts\"",
"precommit": "lint-staged",
"prepublish:npm": "npm run build",
"publish:npm": "npm publish --access public",
"prepublish:next": "npm run build",
"publish:next": "npm publish --access public --tag next",
"prerelease": "npm run build",
"release": "release-it",
"test": "jest -w 1 --no-cache --config jest.json",
"test:dev": "NODE_ENV=test npm run -s test -- --watchAll"
},
"peerDependencies": {
"@azure/functions": "^1.0.3 || ^2.0.0 || ^3.0.0",
"@nestjs/common": "^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0",
"@nestjs/core": "^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0",
"reflect-metadata": "^0.1.13"
},
"devDependencies": {
"@angular-devkit/schematics": "^16.0.0",
"@azure/functions": "3.5.1",
"@commitlint/cli": "19.6.1",
"@commitlint/config-angular": "19.7.0",
"@nestjs/common": "10.2.7",
"@nestjs/core": "10.2.7",
"@nestjs/schematics": "10.0.2",
"@types/node": "22.10.7",
"@types/jest": "29.5.14",
"@typescript-eslint/eslint-plugin": "7.18.0",
"@typescript-eslint/parser": "7.18.0",
"@schematics/angular": "16.2.16",
"eslint": "8.57.1",
"eslint-config-prettier": "10.0.1",
"eslint-plugin-import": "2.31.0",
"husky": "9.1.7",
"lint-staged": "15.4.1",
"prettier": "3.4.2",
"release-it": "17.1.1",
"typescript": "5.7.3",
"jest": "29.7.0",
"ts-jest": "29.2.5"
},
"dependencies": {
"cors": "2.8.5",
"jsonc-parser": "^3.2.0",
"trouter": "3.2.1"
},
"schematics": "./schematics/collection.json",
"lint-staged": {
"*.ts": [
"prettier --write"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -c .commitlintrc.json -E HUSKY_GIT_PARAMS"
}
}
}
================================================
FILE: renovate.json
================================================
{
"semanticCommits": true,
"packageRules": [{
"depTypeList": ["devDependencies"],
"automerge": true
}],
"extends": [
"config:base"
]
}
================================================
FILE: schematics/collection.json
================================================
{
"$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"nest-add": {
"description": "Adds Azure Functions HTTP template to the application without affecting any app files",
"factory": "./install",
"schema": "./install/schema.json",
"aliases": ["nest-azure-shell"]
}
}
}
================================================
FILE: schematics/install/files/project/.funcignore
================================================
*.js.map
*.ts
.git*
.vscode
local.settings.json
test
tsconfig.json
================================================
FILE: schematics/install/files/project/__project__/function.json
================================================
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"route": "<%= getProjectName() %>/{*segments}"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
],
"scriptFile": "../dist/<%= getProjectName() %>/index.js"
}
================================================
FILE: schematics/install/files/project/__project__/index.ts
================================================
import { Context, HttpRequest } from '@azure/functions';
import { AzureHttpAdapter } from '@nestjs/azure-func-http';
import { createApp } from '../apps/<%= getProjectName() %>/src/main.azure';
export default function(context: Context, req: HttpRequest): void {
AzureHttpAdapter.handle(createApp, context, req);
}
================================================
FILE: schematics/install/files/project/__project__/webpack.config.js
================================================
module.exports = function (options) {
return {
...options,
entry: __dirname + '/index.ts',
output: {
libraryTarget: 'commonjs2',
filename: '<%= getProjectName() %>/index.js'
}
};
};
================================================
FILE: schematics/install/files/project/__sourceRoot__/main.azure.ts
================================================
import { INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { <%= getRootModuleName() %> } from './<%= getRootModulePath() %>';
export async function createApp(): Promise {
const app = await NestFactory.create(<%= getRootModuleName() %>);
app.setGlobalPrefix('api/<%= getProjectName() %>');
await app.init();
return app;
}
================================================
FILE: schematics/install/files/project/host.json
================================================
{
"version": "2.0"
}
================================================
FILE: schematics/install/files/project/local.settings.json
================================================
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "node"
}
}
================================================
FILE: schematics/install/files/project/proxies.json
================================================
{
"$schema": "http://json.schemastore.org/proxies",
"proxies": {}
}
================================================
FILE: schematics/install/files/root/.funcignore
================================================
*.js.map
*.ts
.git*
.vscode
local.settings.json
test
tsconfig.json
================================================
FILE: schematics/install/files/root/__rootDir__/main.azure.ts
================================================
import { INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { <%= getRootModuleName() %> } from './<%= getRootModulePath() %>';
export async function createApp(): Promise {
const app = await NestFactory.create(<%= getRootModuleName() %>);
app.setGlobalPrefix('api');
await app.init();
return app;
}
================================================
FILE: schematics/install/files/root/host.json
================================================
{
"version": "2.0"
}
================================================
FILE: schematics/install/files/root/local.settings.json
================================================
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "node"
}
}
================================================
FILE: schematics/install/files/root/main/function.json
================================================
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"route": "{*segments}"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
],
"scriptFile": "../dist/main/index.js"
}
================================================
FILE: schematics/install/files/root/main/index.ts
================================================
import { Context, HttpRequest } from '@azure/functions';
import { AzureHttpAdapter } from '@nestjs/azure-func-http';
import { createApp } from '../<%= getRootDirectory() %>/main.azure';
export default function(context: Context, req: HttpRequest): void {
AzureHttpAdapter.handle(createApp, context, req);
}
================================================
FILE: schematics/install/files/root/proxies.json
================================================
{
"$schema": "http://json.schemastore.org/proxies",
"proxies": {}
}
================================================
FILE: schematics/install/index.test.ts
================================================
import { FileEntry, Tree } from '@angular-devkit/schematics';
import {
SchematicTestRunner,
UnitTestTree
} from '@angular-devkit/schematics/testing';
import * as path from 'path';
import { Schema } from './schema';
const getFileContent = (tree: UnitTestTree, path: string): string => {
const fileEntry: FileEntry = tree.get(path);
if (!fileEntry) {
throw new Error(`The file does not exist.`);
}
return fileEntry.content.toString();
};
describe('Schematic Tests Nest Add', () => {
let nestTree: Tree;
const runner: SchematicTestRunner = new SchematicTestRunner(
'azure-func-http',
path.join(process.cwd(), 'schematics/collection.json')
);
beforeEach(async () => {
nestTree = await createTestNest(runner);
});
describe('Test for default setup', () => {
it('should add azure func for default setup', async () => {
const options: Schema = {
skipInstall: true,
rootModuleFileName: 'app.module',
rootModuleClassName: 'AppModule'
};
const tree = await runner.runSchematic('nest-add', options, nestTree);
const files: string[] = tree.files;
expect(files).toEqual([
'/.eslintrc.js',
'/.prettierrc',
'/README.md',
'/nest-cli.json',
'/package.json',
'/tsconfig.build.json',
'/tsconfig.json',
'/.funcignore',
'/host.json',
'/local.settings.json',
'/proxies.json',
'/src/app.controller.spec.ts',
'/src/app.controller.ts',
'/src/app.module.ts',
'/src/app.service.ts',
'/src/main.ts',
'/src/main.azure.ts',
'/test/app.e2e-spec.ts',
'/test/jest-e2e.json',
'/main/function.json',
'/main/index.ts',
'/main/sample.dat'
]);
});
it('should have a nest-cli.json for default app', async () => {
const options: Schema = {
sourceRoot: 'src',
skipInstall: true,
rootDir: 'src',
rootModuleFileName: 'app.module',
rootModuleClassName: 'AppModule'
};
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = getFileContent(tree, '/nest-cli.json');
expect(fileContent).toContain(`"sourceRoot": "src"`);
});
it('should import the app.module int main azure file for default app', async () => {
const options: Schema = {
sourceRoot: 'src',
skipInstall: true,
rootDir: 'src',
rootModuleFileName: 'app.module',
rootModuleClassName: 'AppModule'
};
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = getFileContent(tree, '/src/main.azure.ts');
expect(fileContent).toContain(
`import { AppModule } from './app.module';`
);
});
it('should have the root dir for index file in main azure dir for default app', async () => {
const options: Schema = {
sourceRoot: 'src',
skipInstall: true,
rootDir: 'src',
rootModuleFileName: 'app.module',
rootModuleClassName: 'AppModule'
};
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = getFileContent(tree, '/main/index.ts');
expect(fileContent).toContain(
`import { createApp } from '../src/main.azure';`
);
});
it('should not import the webpack config for a default app', async () => {
const options: Schema = {
sourceRoot: 'src',
skipInstall: true,
rootDir: 'src',
rootModuleFileName: 'app.module',
rootModuleClassName: 'AppModule'
};
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = tree.get('webpack.config.js');
expect(fileContent).toBeNull();
});
});
describe('Tests for monorepo', () => {
it('should add azure-func for monorepo app', async () => {
const projectName = 'azure-2';
const options: Schema = {
skipInstall: true,
project: projectName,
rootDir: `apps/${projectName}`,
sourceRoot: `apps/${projectName}/src`
};
await runner.runExternalSchematic(
'@nestjs/schematics',
'sub-app',
{
name: projectName
},
nestTree
);
const tree = await runner.runSchematic('nest-add', options, nestTree);
const files: string[] = tree.files;
expect(files).toEqual([
'/.eslintrc.js',
'/.prettierrc',
'/README.md',
'/nest-cli.json',
'/package.json',
'/tsconfig.build.json',
'/tsconfig.json',
'/.funcignore',
'/host.json',
'/local.settings.json',
'/proxies.json',
'/src/app.controller.spec.ts',
'/src/app.controller.ts',
'/src/app.module.ts',
'/src/app.service.ts',
'/src/main.ts',
'/test/app.e2e-spec.ts',
'/test/jest-e2e.json',
'/apps/nestjs-azure-func-http/tsconfig.app.json',
`/apps/${projectName}/tsconfig.app.json`,
`/apps/${projectName}/src/main.ts`,
`/apps/${projectName}/src/${projectName}.controller.spec.ts`,
`/apps/${projectName}/src/${projectName}.controller.ts`,
`/apps/${projectName}/src/${projectName}.module.ts`,
`/apps/${projectName}/src/${projectName}.service.ts`,
`/apps/${projectName}/src/main.azure.ts`,
`/apps/${projectName}/test/jest-e2e.json`,
`/apps/${projectName}/test/app.e2e-spec.ts`,
`/${projectName}/function.json`,
`/${projectName}/index.ts`,
`/${projectName}/sample.dat`,
`/${projectName}/webpack.config.js`
]);
});
it('should have a nest-cli.json for monorepo app', async () => {
const projectName = 'azure-2';
const options: Schema = {
skipInstall: true,
project: projectName,
sourceRoot: `apps/${projectName}/src`
};
await runner.runExternalSchematic(
'@nestjs/schematics',
'sub-app',
{
name: projectName
},
nestTree
);
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = getFileContent(tree, '/nest-cli.json');
const parsedFile = JSON.parse(fileContent);
expect(parsedFile.projects[projectName].sourceRoot).toEqual(
`apps/${projectName}/src`
);
});
it('should import the app.module int main azure file for monorepo app', async () => {
const projectName = 'azure-2';
const options: Schema = {
skipInstall: true,
project: projectName,
sourceRoot: `apps/${projectName}/src`
};
await runner.runExternalSchematic(
'@nestjs/schematics',
'sub-app',
{
name: projectName
},
nestTree
);
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = getFileContent(
tree,
`/apps/${projectName}/src/main.azure.ts`
);
expect(fileContent).toContain(
`import { AppModule } from './app.module';`
);
});
it('should have the root dir for index file in main azure dir for monorepo app', async () => {
const projectName = 'azure-2';
const options: Schema = {
skipInstall: true,
project: projectName,
sourceRoot: `apps/${projectName}/src`
};
await runner.runExternalSchematic(
'@nestjs/schematics',
'sub-app',
{
name: projectName
},
nestTree
);
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = getFileContent(tree, `/${projectName}/index.ts`);
expect(fileContent).toContain(
`import { createApp } from '../apps/${projectName}/src/main.azure';`
);
});
it('should import the webpack config for monorepo app', async () => {
const projectName = 'azure-2';
const options: Schema = {
skipInstall: true,
project: projectName,
rootDir: `apps/${projectName}`,
sourceRoot: `apps/${projectName}/src`
};
await runner.runExternalSchematic(
'@nestjs/schematics',
'sub-app',
{
name: projectName
},
nestTree
);
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = getFileContent(
tree,
`/${projectName}/webpack.config.js`
);
expect(fileContent).toContain(`filename: '${projectName}/index.js'`);
});
it('should add a custom webpack config to the compilerOptions for monorepo app', async () => {
const projectName = 'azure-2';
const options: Schema = {
skipInstall: true,
project: projectName,
sourceRoot: `apps/${projectName}/src`
};
await runner.runExternalSchematic(
'@nestjs/schematics',
'sub-app',
{
name: projectName
},
nestTree
);
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = getFileContent(tree, 'nest-cli.json');
const parsedFile = JSON.parse(fileContent);
const compilerOptions = parsedFile.projects[projectName].compilerOptions;
expect(compilerOptions).toEqual({
tsConfigPath: `apps/${projectName}/tsconfig.app.json`,
webpack: true,
webpackConfigPath: `${projectName}/webpack.config.js`
});
});
it('should the scriptFile of functions to sub dir for monorepo app', async () => {
const projectName = 'azure-2';
const options: Schema = {
skipInstall: true,
project: projectName,
rootDir: `apps.${projectName}`,
sourceRoot: `apps/${projectName}/src`
};
await runner.runExternalSchematic(
'@nestjs/schematics',
'sub-app',
{
name: projectName
},
nestTree
);
const tree = await runner.runSchematic('nest-add', options, nestTree);
const fileContent = getFileContent(tree, `${projectName}/function.json`);
const parsedFile = JSON.parse(fileContent);
expect(parsedFile.scriptFile).toEqual(`../dist/${projectName}/index.js`);
});
});
async function createTestNest(
runner: SchematicTestRunner,
tree?: Tree
): Promise {
return await runner.runExternalSchematic(
'@nestjs/schematics',
'application',
{
name: 'newproject',
directory: '.'
},
tree
);
}
});
================================================
FILE: schematics/install/index.ts
================================================
import { strings } from '@angular-devkit/core';
import { parse as parseJson } from 'jsonc-parser';
import {
apply,
chain,
FileEntry,
forEach,
mergeWith,
noop,
Rule,
SchematicContext,
SchematicsException,
template,
Tree,
url
} from '@angular-devkit/schematics';
import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
import {
addPackageJsonDependency,
NodeDependencyType
} from '@schematics/angular/utility/dependencies';
import { Schema as AzureOptions } from './schema';
type UpdateJsonFn = (obj: T) => T | void;
function addDependenciesAndScripts(): Rule {
return (host: Tree) => {
addPackageJsonDependency(host, {
type: NodeDependencyType.Default,
name: '@azure/functions',
version: '^1.0.3'
});
const pkgPath = '/package.json';
const buffer = host.read(pkgPath);
if (buffer === null) {
throw new SchematicsException('Could not find package.json');
}
const pkg = JSON.parse(buffer.toString());
pkg.scripts['start:azure'] = 'npm run build && func host start';
host.overwrite(pkgPath, JSON.stringify(pkg, null, 2));
return host;
};
}
function updateJsonFile(
host: Tree,
path: string,
callback: UpdateJsonFn
): Tree {
const source = host.read(path);
if (source) {
const sourceText = source.toString('utf-8');
const json = parseJson(sourceText);
callback(json as {} as T);
host.overwrite(path, JSON.stringify(json, null, 2));
}
return host;
}
const applyProjectName = (projectName, host) => {
if (projectName) {
let nestCliFileExists = host.exists('nest-cli.json');
if (nestCliFileExists) {
updateJsonFile(
host,
'nest-cli.json',
(optionsFile: Record) => {
if (optionsFile.projects[projectName].compilerOptions) {
optionsFile.projects[projectName].compilerOptions = {
...optionsFile.projects[projectName].compilerOptions,
...{
webpack: true,
webpackConfigPath: `${projectName}/webpack.config.js`
}
};
}
}
);
}
}
};
const rootFiles = [
'/.funcignore',
'/host.json',
'/local.settings.json',
'/proxies.json'
];
const validateExistingRootFiles = (host: Tree, file: FileEntry) => {
return rootFiles.includes(file.path) && host.exists(file.path);
};
export default function (options: AzureOptions): Rule {
return (host: Tree, context: SchematicContext) => {
if (!options.skipInstall) {
context.addTask(new NodePackageInstallTask());
}
const defaultSourceRoot =
options.project !== undefined ? options.sourceRoot : options.rootDir;
const rootSource = apply(
options.project ? url('./files/project') : url('./files/root'),
[
template({
...strings,
...(options as AzureOptions),
rootDir: options.rootDir,
sourceRoot: defaultSourceRoot,
getRootDirectory: () => options.rootDir,
getProjectName: () => options.project,
stripTsExtension: (s: string) => s.replace(/\.ts$/, ''),
getRootModuleName: () => options.rootModuleClassName,
getRootModulePath: () => options.rootModuleFileName
}),
forEach((file: FileEntry) => {
if (validateExistingRootFiles(host, file)) return null;
return file;
})
]
);
return chain([
(tree, context) =>
options.project
? applyProjectName(options.project, host)
: noop()(tree, context),
addDependenciesAndScripts(),
mergeWith(rootSource)
]);
};
}
================================================
FILE: schematics/install/schema.json
================================================
{
"$schema": "http://json-schema.org/schema",
"$id": "SchematicsNestEngineInstall",
"title": "Nest Engine Install Options Schema",
"type": "object",
"properties": {
"rootDir": {
"type": "string",
"description": "Application root directory.",
"default": "src"
},
"rootModuleFileName": {
"type": "string",
"format": "path",
"description": "The name of the root module file (without extension)",
"default": "app.module"
},
"rootModuleClassName": {
"type": "string",
"description": "The name of the root module class.",
"default": "AppModule"
},
"skipInstall": {
"description": "Skip installing dependency packages.",
"type": "boolean",
"default": false
},
"sourceRoot": {
"type": "string",
"description": "The source root directory."
},
"project": {
"type": "string",
"description": "The project where generate the azure files."
}
},
"required": []
}
================================================
FILE: schematics/install/schema.ts
================================================
export interface Schema {
/**
* Application root directory
*/
rootDir?: string;
/**
* The name of the root module file
*/
rootModuleFileName?: string;
/**
* The name of the root module class.
*/
rootModuleClassName?: string;
/**
* Skip installing dependency packages.
*/
skipInstall?: boolean;
/**
* .
*/
sourceRoot?: string;
/**
* The project where generate the azure files.
*/
project?: string;
}
================================================
FILE: tsconfig.json
================================================
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "ES2021",
"sourceMap": false,
"outDir": "./dist",
"skipLibCheck": true
},
"include": ["lib/**/*", "../index.ts"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
================================================
FILE: tsconfig.schematics.json
================================================
{
"compilerOptions": {
"rootDir": "schematics",
"outDir": "./schematics"
},
"extends": "./tsconfig.json",
"include": ["schematics/**/*"],
"exclude": ["node_modules", "**/*.spec.ts", "./schematics/install/files/**"]
}