Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Marplex committed Mar 6, 2024
1 parent 7635551 commit ccb311c
Show file tree
Hide file tree
Showing 10 changed files with 269 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/publish_ghpackages.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Publish package to GitHub Packages
on:
release:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18.4.0'
registry-url: 'https://npm.pkg.github.com'
scope: '@marplex'
- name: Install dependencies
run: npm install
- name: Setup github package registry
run: 'echo "registry=https://npm.pkg.github.com/@marplex" >> .npmrc'
- name: Build
run: npm run build
- name: Publish
run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
22 changes: 22 additions & 0 deletions .github/workflows/publish_npm.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: Publish Package to npmjs
on:
release:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@v3
with:
node-version: '18.4.0'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: npm install
- name: Build
run: npm run build
- name: Publish
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Marco

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.
92 changes: 92 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<h1 align="center">hono-azurefunc-adapter</h1>
<p align="center">
Azure Functions V4 adapter for Hono. Run Hono on Azure Functions.
</p>
<br>

<p align="center">
<a href="https://github.com/marplex/hono-azurefunc-adapter/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/marplex/hono-azurefunc-adapter"/></a>
<img src="https://github.com/marplex/hono-azurefunc-adapter/actions/workflows/node_ci.yaml/badge.svg" alt="GitHub CI"/>
<a href="https://www.npmjs.com/package/@marplex/hono-azurefunc-adapter"><img alt="NPM" src="https://badge.fury.io/js/@marplex%2Fhono-azurefunc-adapter.svg"/></a>
<a href="https://www.npmjs.com/package/@marplex/hono-azurefunc-adapter"><img src="https://img.shields.io/npm/dt/@marplex/hono-azurefunc-adapter.svg" alt="NPM Downloads"/></a>
<a href="https://github.com/Marplex"><img alt="Github" src="https://img.shields.io/static/v1?label=GitHub&message=marplex&color=005cb2"/></a>
</p>

# Install

```bash
npm i @marplex/hono-azurefunc-adapter
```

# Getting started
The adapter exposes an handler that converts between standard web Request/Response (used by Hono) and HttpRequest/HttpResponse (used by Azure Functions). This handler is then called by the function http trigger.

```typescript
//app.ts

import { Hono } from "hono";
const app = new Hono();

...

export default app
```

```typescript
//httpTrigger.ts

import honoApp from "./app";

import { azureHonoHandler } from "@marplex/hono-azurefunc-adapter";
import { app } from "@azure/functions";

app.http("httpTrigger", {
methods: [
"GET",
"POST",
"DELETE",
"HEAD",
"PATCH",
"PUT",
"OPTIONS",
"TRACE",
"CONNECT",
],
authLevel: "anonymous",
route: "{*proxy}",
handler: azureHonoHandler(honoApp.fetch),
});
```

# Limitations

There are some limitations and other things you should keep in mind when running Hono inside Azure Functions.

### Route Prefix

The default Azure Functions route prefix is `/api`. Be sure to start all your Hono routes with `/api` or change the default Azure Functions route prefix in `host.json`

```json
//host.json
{
[...]

"extensions": {
"http": {
"routePrefix": ""
}
}
}
```

### Crypto

If you are using `hono/bearer-auth` or any other library that uses crypto, be sure to define `global.crypto = require("crypto");` before registering the http trigger.

### Request signal

Azure Functions does not expose any signal or event for listening to http request interruptions. `c.req.raw.signal` is useless and its never aborted.

# Untested scenarios

- SSE (streaming response)
25 changes: 25 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "@marplex/hono-azurefunc-adapter",
"version": "1.0.0",
"description": "Azure Functions adapter for Hono. Run Hono on Azure Functions.",
"keywords": ["hono","azure functions", "serverless", "http", "http framework"],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist",
"README.md",
"LICENSE"
],
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"@azure/functions": "^4.1.0",
"@types/node": "^20.10.0",
"hono": "^4.0.3",
"typescript": "^5.3.2"
},
"license": "MIT"
}
15 changes: 15 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { HttpRequest, InvocationContext } from "@azure/functions";
import { newRequestFromAzureFunctions } from "./request";
import { newAzureFunctionsResponse } from "./response";

export type FetchCallback = (
request: Request,
env: Record<string, unknown>
) => Promise<Response> | Response;

export function azureHonoHandler(fetch: FetchCallback) {
return async (request: HttpRequest, _context: InvocationContext) =>
newAzureFunctionsResponse(
await fetch(newRequestFromAzureFunctions(request), process.env)
);
}
12 changes: 12 additions & 0 deletions src/request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { HttpRequest } from "@azure/functions";
import { headersToObject } from "./utils";

export const newRequestFromAzureFunctions = (request: HttpRequest): Request => {
const hasBody = !["GET", "HEAD"].includes(request.method);

return new Request(request.url, {
method: request.method,
headers: headersToObject(request.headers),
...(hasBody ? { body: request.body, duplex: "half" } : {}),
});
};
10 changes: 10 additions & 0 deletions src/response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { HttpResponseInit } from "@azure/functions";
import { headersToObject, streamToAsyncIterator } from "./utils";

export const newAzureFunctionsResponse = (
response: Response
): HttpResponseInit => ({
status: response.status,
headers: headersToObject(response.headers),
body: streamToAsyncIterator(response.body),
})
24 changes: 24 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export const streamToAsyncIterator = (readable: ReadableStream<Uint8Array>) => {
const reader = readable.getReader();
return {
next() {
return reader.read();
},
return() {
return reader.releaseLock();
},
[Symbol.asyncIterator]() {
return this;
},
} as AsyncIterableIterator<Uint8Array>;
};

type LoopableHeader = {
forEach: (callbackfn: (value: string, key: string) => void) => void;
};

export function headersToObject(input: LoopableHeader): Record<string, string> {
const headers: Record<string, string> = {};
input.forEach((v, k) => (headers[k] = v));
return headers;
}
21 changes: 21 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "es2022",
"module": "commonjs",
"declaration": true,
"moduleResolution": "Node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"types": [
"node",
],
"rootDir": "./src",
"outDir": "./dist",
},
"include": [
"src/**/*.ts"
],
}

0 comments on commit ccb311c

Please sign in to comment.