Skip to content

Commit

Permalink
Merge pull request #202 from ThorstenHans/feature/router-samples
Browse files Browse the repository at this point in the history
Add samples for built-in HTTP router (JS & TS)
  • Loading branch information
vdice authored Oct 20, 2023
2 parents d9c720a + 82382db commit 797569b
Show file tree
Hide file tree
Showing 17 changed files with 3,307 additions and 0 deletions.
4 changes: 4 additions & 0 deletions examples/javascript/http-router/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
dist
target
.spin/
15 changes: 15 additions & 0 deletions examples/javascript/http-router/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# `spin-js-sdk` HTTP router sample

This app demonstrates how one can use the built-in router in JavaScript to address routing concerns.

The app exposes the following endpoints:

- `GET /ok`: Endpoint that will always return HTTP 200
- `GET /echo/:value?`: Endpoint with an optional route parameter (`:value?`)
- `POST /format-json`: Endpoint that relies on the request payload to build the response
- `POST /start-job`: Endpoint that uses a middleware
- `* /*`: a catch-all route that always returns HTTP 404

## Build and run the app locally

To build and run the app locally, you can either use `spin build` and `spin up` or combine both commands and simply run `spin build --up`.
1,395 changes: 1,395 additions & 0 deletions examples/javascript/http-router/package-lock.json

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions examples/javascript/http-router/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "http-router",
"version": "1.0.0",
"description": "Sample to demonstrate the usage of the HTTP router",
"main": "index.js",
"scripts": {
"build": "npx webpack --mode=production && mkdir -p target && spin js2wasm -o target/http-router.wasm dist/spin.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
},
"dependencies": {
"@fermyon/spin-sdk": "0.6.0-rc.0"
}
}
15 changes: 15 additions & 0 deletions examples/javascript/http-router/spin.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
spin_manifest_version = "1"
authors = ["Thorsten Hans <[email protected]>"]
description = "Sample to demonstrate the usage of the HTTP router"
name = "http-router"
trigger = { type = "http", base = "/" }
version = "0.1.0"

[[component]]
id = "http-router"
source = "target/http-router.wasm"
exclude_files = ["**/node_modules"]
[component.trigger]
route = "/..."
[component.build]
command = "npm run build"
68 changes: 68 additions & 0 deletions examples/javascript/http-router/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Router } from '@fermyon/spin-sdk'
import { withCorrelationId } from './middlewares'

const encoder = new TextEncoder()
const decoder = new TextDecoder()

const router = new Router()

// register a simple inline handler
router.get("/ok", () => ({ status: 200 }))
// use route parameters
router.get("/echo/:value?", ({ params }) => echo(params.value))
// register routes for different HTTP methods
router.post("/format-json", ({ }, body) => formatJson(body))
// use middlewares
router.post("/start-job", withCorrelationId, ({ correlationId }) => startJob(correlationId))
// catch all route to send 404 for all other requests
router.all("*", () => ({
status: 404,
body: encoder.encode("Not found")
}))

/// handler for the /start-job route
const startJob = (correlationId) => {
const job = {
name: "Sample Job",
status: "started",
correlationId,
}
return {
status: 200,
body: encoder.encode(JSON.stringify(job))
}
}

// handler for the /format-json route
const formatJson = (body) => {
try {
console.log(body)
const json = JSON.parse(decoder.decode(body))
return {
status: 200,
body: encoder.encode(JSON.stringify(json, null, 2))
}
} catch (e) {
return {
status: 400,
body: encoder.encode("Invalid JSON provided, sorry!")
}
}
}

/// handler for the /echo route
const echo = (value) => {
if (!value) {
return {
status: 204
}
}
return {
status: 200,
body: value
}
}

export async function handleRequest(request) {
return router.handleRequest(request, request.body)
}
7 changes: 7 additions & 0 deletions examples/javascript/http-router/src/middlewares.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/// this middleware adds a correlationId to the request object
const withCorrelationId = (request) => {
request.correlationId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
}

// export all middlewares as an object
export { withCorrelationId }
13 changes: 13 additions & 0 deletions examples/javascript/http-router/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const path = require('path');

module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'spin.js',
library: 'spin'
},
optimization: {
minimize: false
},
};
4 changes: 4 additions & 0 deletions examples/typescript/http-router/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
dist
target
.spin/
15 changes: 15 additions & 0 deletions examples/typescript/http-router/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# `spin-js-sdk` HTTP router sample (TS)

This app demonstrates how one can use the built-in router in TypeScript to address routing concerns.

The app exposes the following endpoints:

- `GET /ok`: Endpoint that will always return HTTP 200
- `GET /echo/:value?`: Endpoint with an optional route parameter (`:value?`)
- `POST /format-json`: Endpoint that relies on the request payload to build the response
- `POST /start-job`: Endpoint that uses a middleware
- `* /*`: a catch-all route that always returns HTTP 404

## Build and run the app locally

To build and run the app locally, you can either use `spin build` and `spin up` or combine both commands and simply run `spin build --up`.
Loading

0 comments on commit 797569b

Please sign in to comment.