@curveball/kernel
Version:
Curveball is a framework writting in Typescript for Node.js
100 lines • 2.81 kB
JavaScript
export class Headers {
store;
constructor(headersObj = {}) {
this.store = {};
for (const key of Object.keys(headersObj)) {
this.set(key, headersObj[key]);
}
}
/**
* Sets a HTTP header name and value.
*/
set(name, value) {
// Storing the header name case-insenstive, but we retain the original
// case as well.
this.store[name.toLowerCase()] = [name, value];
}
/**
* Gets a HTTP header's value.
*
* This function will return null if the header did not exist. If it did
* exist, it will return a string.
*
* If there were multiple headers with the same value, it will join the
* headers with a comma.
*/
get(name) {
const tuple = this.store[name.toLowerCase()];
if (tuple === undefined) {
return null;
}
const value = tuple[1];
if (typeof (value) === 'string') {
return value;
}
else if (Array.isArray(value)) {
return value.join(', ');
}
else {
return value.toString();
}
}
/**
* Gets all values of a HTTP header
*
* This function will return an array with 0 or more values of a header.
*
*/
getMany(name) {
const tuple = this.store[name.toLowerCase()];
if (tuple === undefined) {
return [];
}
const value = tuple[1];
if (Array.isArray(value)) {
return value;
}
else {
return [value.toString()];
}
}
/**
* Returns true or false depending on if a HTTP header exists.
*/
has(name) {
return this.store[name.toLowerCase()] !== undefined;
}
/**
* Returns all HTTP headers.
*
* Headernames are lowercased. Values may be either strings or arrays of
* strings or numbers.
*/
getAll() {
const result = {};
for (const headerName of Object.keys(this.store)) {
result[headerName] = this.store[headerName][1];
}
return result;
}
/**
* Appends a new header, without removing an old one with the same name.
*/
append(name, value) {
const lowerName = name.toLowerCase();
if (this.store[lowerName] === undefined) {
this.store[lowerName] = [name, value];
return;
}
const oldArray = Array.isArray(this.store[lowerName][1]) ? this.store[lowerName][1] : [this.store[lowerName][1].toString()];
this.store[lowerName][1] = oldArray.concat(value);
}
/**
* Removes a HTTP header
*/
delete(name) {
delete this.store[name.toLowerCase()];
}
}
export default Headers;
//# sourceMappingURL=headers.js.map