Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 736647f

Browse files
authored
Merge pull request #266 from Taillis-Labs/my-branch-dev
feat(server): `redirect` replies to redirect the client to another URL
2 parents 0cc867e + c046075 commit 736647f

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

server/api.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { BufReader, BufWriter } from 'https://deno.land/[email protected]/io/bufio.ts'
22
import type { MultipartFormData } from 'https://deno.land/[email protected]/mime/multipart.ts'
33
import { MultipartReader } from 'https://deno.land/[email protected]/mime/multipart.ts'
4+
import { Status } from "https://deno.land/[email protected]/http/http_status.ts";
45
import log from '../shared/log.ts'
56
import type { APIRequest, ServerRequest, ServerResponse } from '../types.ts'
67

@@ -126,6 +127,16 @@ export class Request implements APIRequest {
126127
return this
127128
}
128129

130+
redirect(url: string, status: Status = Status.Found): this {
131+
// "back" is an alias for the referrer.
132+
if (url == "back") {
133+
url = this.#resp.headers.get("Referrer") || "/"
134+
}
135+
this.#resp.status = status
136+
this.#resp.headers.set("Location", encodeURI(url))
137+
return this
138+
}
139+
129140
async send(data?: string | Uint8Array | ArrayBuffer, contentType?: string): Promise<void> {
130141
if (this.#resp.done) {
131142
log.warn('ServerRequest: repeat respond calls')

types.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { BufReader, BufWriter } from 'https://deno.land/[email protected]/io/bufio.ts'
22
import type { MultipartFormData } from 'https://deno.land/[email protected]/mime/multipart.ts'
3+
import type { Status } from "https://deno.land/[email protected]/http/http_status.ts"
34
import { Plugin, PluginCreator } from 'https://esm.sh/[email protected]'
45

56
/**
@@ -181,6 +182,8 @@ export interface APIRequest extends ServerRequest {
181182
send(data?: string | Uint8Array | ArrayBuffer, contentType?: string): Promise<void>
182183
/** `json` replies to the request with a json content. */
183184
json(data: any): Promise<void>
185+
/** `redirect` replies to redirect the client to another URL with optional response `status` defaulting to 302. */
186+
redirect(url: string, status?: Status): this
184187
}
185188

186189
/**

0 commit comments

Comments
 (0)