Add support for responses

This commit is contained in:
2021-03-07 09:58:21 -06:00
parent e298319bf5
commit 94add3d471
4 changed files with 207 additions and 7 deletions

View File

@@ -1,5 +1,5 @@
import {Request} from "../lifecycle/Request";
import {infer} from "@extollo/util";
import {uninfer, infer, uuid_v4} from "@extollo/util";
/**
* Base type representing a parsed cookie.
@@ -9,10 +9,22 @@ export interface HTTPCookie {
originalValue: string,
value: any,
exists: boolean,
options?: HTTPCookieOptions,
}
export type MaybeHTTPCookie = HTTPCookie | undefined;
export interface HTTPCookieOptions {
domain?: string,
expires?: Date, // encodeURIComponent
httpOnly?: boolean,
maxAge?: number,
path?: string,
secure?: boolean,
signed?: boolean,
sameSite?: 'strict' | 'lax' | 'none-secure',
}
export class HTTPCookieJar {
protected parsed: {[key: string]: HTTPCookie} = {}
@@ -28,6 +40,79 @@ export class HTTPCookieJar {
}
}
set(name: string, value: any, options?: HTTPCookieOptions) {
this.parsed[name] = {
key: name,
value,
originalValue: uninfer(value),
exists: false,
options,
}
}
clear(name: string, options?: HTTPCookieOptions) {
if ( !options ) options = {}
options.expires = new Date(0)
this.parsed[name] = {
key: name,
value: undefined,
originalValue: uuid_v4(),
exists: false,
options,
}
}
getSetCookieHeaders(): string[] {
const headers: string[] = []
for ( const key in this.parsed ) {
if ( !this.parsed.hasOwnProperty(key) ) continue
const cookie = this.parsed[key]
const parts = []
parts.push(`${key}=${encodeURIComponent(cookie.originalValue)}`)
if ( cookie.options?.expires ) {
parts.push(`Expires=${cookie.options.expires.toUTCString()}`)
}
if ( cookie.options?.maxAge ) {
parts.push(`Max-Age=${Math.floor(cookie.options.maxAge)}`)
}
if ( cookie.options?.domain ) {
parts.push(`Domain=${cookie.options.domain}`)
}
if ( cookie.options?.path ) {
parts.push(`Path=${cookie.options.path}`)
}
if ( cookie.options?.secure ) {
parts.push('Secure')
}
if ( cookie.options?.httpOnly ) {
parts.push('HttpOnly')
}
if ( cookie.options?.sameSite ) {
const map = {
strict: 'Strict',
lax: 'Lax',
'none-secure': 'None; Secure'
}
parts.push(map[cookie.options.sameSite])
}
headers.push(parts.join('; '))
}
return headers
}
private parseCookies() {
const cookies = String(this.request.getHeader('cookie'))
cookies.split(';').forEach(cookie => {