Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TS example of handling POST data from a router. #1046

Merged
merged 3 commits into from
Nov 21, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions content/api/hub/sample_ts_router_post.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
title = "Handle POST Requests with Spin's JS/TS Router"
template = "render_hub_content_body"
date = "2023-11-15T00:00:00Z"
content-type = "text/html"
tags = ["typescript", "javascript", "router"]

[extra]
author = "technosophos"
type = "hub_document"
category = "Sample"
language = "JS/TS"
created_at = "2023-11-15T00:00:00Z"
last_updated = "2023-11-15T00:00:00Z"
spin_version = ">v2.0"
summary = "Handle POST data from within Spin's JS/TS Router"
url = "https://github.com/technosophos/ts-router-post"
keywords = "typescript, javascript, router"

---

This shows one technique for handling POST data using the `Router` object [built into the JS/TS SDK](https://developer.fermyon.com/spin/v2/javascript-components) for Spin.

This example illustrates how to pass the HTTP body from Spin's SDK all the way to your end function without needing to use middleware.

```typescript
export const handleRequest: HandleRequest = async function (request: HttpRequest): Promise<HttpResponse> {
let router = Router()

// This gets the base path from the request, which is considered better
// than hardcoding it. Now, when the `route` is changed in spin.toml,
// our code does not need to change.
let basePath = request.headers["spin-component-route"]

// Note that we pass `request.body` as the second param.
// That contains an ArrayBuffer with the encoded body.
router.post(basePath, (req, body) => {

// Decode the ArrayBuffer into a string
let decodedBody = decoder.decode(body)
return {
status: 200,
headers: { "content-type": "text/plain" },
body: decodedBody
}
})
// IMPORTANT: We pass the request body as the second param.
return await router.handleRequest(request, request.body)
}
```

Check out the GitHub repository for a full runnable example.