Skip to content

Commit

Permalink
feat: support backend option for fastly (#31)
Browse files Browse the repository at this point in the history
* feat: support backend option for fastly

* fix: make backend optional
  • Loading branch information
chronark authored Mar 8, 2022
1 parent a24cb7a commit 15b9475
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 14 deletions.
28 changes: 14 additions & 14 deletions examples/fastly/src/index.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { Router } from "flight-path"
import { auth, incr } from "@upstash/redis"
import { Redis } from "@upstash/redis"

const router = new Router()
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)))

auth({
url: "UPSTASH_REDIS_REST_URL",
token: "UPSTASH_REDIS_REST_TOKEN",
requestOptions: { backend: "upstash-db" },
})
async function handleRequest(event) {
const redis = new Redis({
url: "<UPSTASH_REDIS_REST_URL>",
token: "<UPSTASH_REDIS_REST_TOKEN>",
requestOptions: { backend: "upstash-db" },
})

router.get("/", async (req, res) => {
const { data: count } = await incr("count")
res.send(`Fastly with Upstash! Count: ${count}`)
})

router.listen()
const counter = await redis.incr("fastly")
// Catch all other requests and return a 404.
return new Response(`Counter: ${counter}`, {
status: 404,
})
}
8 changes: 8 additions & 0 deletions pkg/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,22 @@ export type UpstashResponse<TResult> = {
export type HttpClientConfig = {
headers?: Record<string, string>
baseUrl: string
options?: {
backend?: string
}
}

export class HttpClient {
public baseUrl: string
public headers: Record<string, string>
public readonly options?: { backend?: string }

public constructor(config: HttpClientConfig) {
this.baseUrl = config.baseUrl.replace(/\/$/, "")

this.headers = config.headers ?? {}

this.options = config.options
}

private async request<TResponse>(
Expand All @@ -52,6 +58,8 @@ export class HttpClient {
method,
headers,
body: JSON.stringify(req.body),
// @ts-expect-error
backend: this.options?.backend,
})
const body = await res.json()
if (!res.ok) {
Expand Down
12 changes: 12 additions & 0 deletions pkg/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,17 @@ export type RedisConfig = {
* UPSTASH_REDIS_REST_TOKEN
*/
token: string

requestOptions?: {
/**
* **fastly only**
*
* A Request can be forwarded to any backend defined on your service. Backends
* can be created via the Fastly CLI, API, or web interface, and are
* referenced by name.
*/
backend?: string
}
}

/**
Expand All @@ -153,6 +164,7 @@ export class Redis {
headers: {
authorization: `Bearer ${config.token}`,
},
options: config.requestOptions,
})
}

Expand Down

0 comments on commit 15b9475

Please sign in to comment.