@chubbyts/chubbyts-http
Version:
Http Request/Response with middleware and handler, PSR-15 inspired.
75 lines (74 loc) • 2.6 kB
JavaScript
import { createReadStream, existsSync } from 'fs';
import { PassThrough } from 'stream';
import { statusMap } from '@chubbyts/chubbyts-http-types/dist/message';
import { parse as queryParser } from 'qs';
export const createUriFactory = () => {
return (uri) => {
const { protocol, username, password, hostname, port, pathname, search, hash } = new URL(uri);
return {
schema: protocol.substring(0, protocol.length - 1),
userInfo: password !== '' ? username + ':' + password : username,
host: hostname,
port: port ? parseInt(port, 10) : undefined,
path: pathname,
query: search ? queryParser(search.substring(1)) : {},
fragment: hash ? hash.substring(1) : '',
};
};
};
export const createStreamFactory = () => {
return (content) => {
const stream = new PassThrough();
stream.write(content);
return stream;
};
};
export const createStreamFromResourceFactory = () => {
return (stream) => {
const newStream = new PassThrough();
stream.pipe(newStream);
return newStream;
};
};
export const createStreamFromFileFactory = (streamFromResourceFactory = createStreamFromResourceFactory()) => {
return (filename) => {
if (!existsSync(filename)) {
throw new Error(`File with filename: "${filename}" does not exists.`);
}
return streamFromResourceFactory(createReadStream(filename));
};
};
export const createRequestFactory = (uriFactory = createUriFactory(), streamFactory = createStreamFactory()) => {
return (method, uri) => {
return {
method,
uri: typeof uri !== 'string' ? { ...uri } : uriFactory(uri),
protocolVersion: '1.0',
headers: {},
body: streamFactory(''),
};
};
};
export const createServerRequestFactory = (requestFactory = createRequestFactory()) => {
return (method, uri) => {
return {
...requestFactory(method, uri),
attributes: {},
};
};
};
/**
* @deprecated Use `statusMap` (import { statusMap } from '@chubbyts/chubbyts-http-types/dist/message';).
*/
export const statusCodeMap = statusMap;
export const createResponseFactory = (streamFactory = createStreamFactory()) => {
return (status, reasonPhrase) => {
return {
status,
reasonPhrase: reasonPhrase ?? statusMap.get(status) ?? '',
protocolVersion: '1.0',
headers: {},
body: streamFactory(''),
};
};
};