Add basic response factories and helpers
This commit is contained in:
@@ -5,7 +5,7 @@ import {HTTPCookieJar} from "../kernel/HTTPCookieJar";
|
||||
import {TLSSocket} from "tls";
|
||||
import * as url from "url";
|
||||
import {Response} from "./Response";
|
||||
import {ActivatedRoute} from "../routing/ActivatedRoute";
|
||||
import * as Negotiator from "negotiator";
|
||||
|
||||
// FIXME - add others?
|
||||
export type HTTPMethod = 'post' | 'get' | 'patch' | 'put' | 'delete' | 'unknown';
|
||||
@@ -41,6 +41,7 @@ export class Request extends ScopedContainer {
|
||||
public readonly isXHR: boolean;
|
||||
public readonly address: HTTPSourceAddress;
|
||||
public readonly response: Response;
|
||||
public readonly mediaTypes: string[];
|
||||
|
||||
constructor(
|
||||
protected clientRequest: IncomingMessage,
|
||||
@@ -98,6 +99,7 @@ export class Request extends ScopedContainer {
|
||||
port
|
||||
}
|
||||
|
||||
this.mediaTypes = (new Negotiator(clientRequest)).mediaTypes()
|
||||
this.response = new Response(this, serverResponse)
|
||||
}
|
||||
|
||||
@@ -115,10 +117,33 @@ export class Request extends ScopedContainer {
|
||||
}
|
||||
}
|
||||
|
||||
// session
|
||||
// route
|
||||
// respond
|
||||
// body
|
||||
accepts(type: string) {
|
||||
if ( type === 'json' ) type = 'application/json'
|
||||
else if ( type === 'xml' ) type = 'application/xml'
|
||||
else if ( type === 'html' ) type = 'text/html'
|
||||
|
||||
type = type.toLowerCase()
|
||||
|
||||
const possible = [
|
||||
type,
|
||||
type.split('/')[0] + '/*',
|
||||
'*/*'
|
||||
]
|
||||
|
||||
return this.mediaTypes.some(media => possible.includes(media.toLowerCase()))
|
||||
}
|
||||
|
||||
wants(): 'html' | 'json' | 'xml' | 'unknown' {
|
||||
const jsonIdx = this.mediaTypes.indexOf('application/json') ?? this.mediaTypes.indexOf('application/*') ?? this.mediaTypes.indexOf('*/*')
|
||||
const xmlIdx = this.mediaTypes.indexOf('application/xml') ?? this.mediaTypes.indexOf('application/*') ?? this.mediaTypes.indexOf('*/*')
|
||||
const htmlIdx = this.mediaTypes.indexOf('text/html') ?? this.mediaTypes.indexOf('text/*') ?? this.mediaTypes.indexOf('*/*')
|
||||
|
||||
if ( htmlIdx >= 0 && htmlIdx <= jsonIdx && htmlIdx <= xmlIdx ) return 'html'
|
||||
if ( jsonIdx >= 0 && jsonIdx <= htmlIdx && jsonIdx <= xmlIdx ) return 'json'
|
||||
if ( xmlIdx >= 0 && xmlIdx <= jsonIdx && xmlIdx <= htmlIdx ) return 'xml'
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
// hostname
|
||||
|
||||
/*
|
||||
@@ -127,8 +152,7 @@ export class Request extends ScopedContainer {
|
||||
fresh/stale - cache
|
||||
remote ips (proxy)
|
||||
signedCookies
|
||||
accepts content type, charsets, encodings, languages
|
||||
is content type (wants)
|
||||
accepts charsets, encodings, languages
|
||||
range header parser
|
||||
*/
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user