Skip to content

Instantly share code, notes, and snippets.

@dcherman
Created February 1, 2018 19:23
Show Gist options
  • Save dcherman/5b84d0598c7e985e125b130e05dfea3e to your computer and use it in GitHub Desktop.
Save dcherman/5b84d0598c7e985e125b130e05dfea3e to your computer and use it in GitHub Desktop.
import { BaseHttpController as InversifyBaseHttpController, interfaces } from 'inversify-express-utils';
export class BaseHttpController extends InversifyBaseHttpController {
public ok(content: any) {
return new HttpResponseMessage(this.httpContext, { statusCode: 200, content });
}
public created(location: string, content?: any) {
return new HttpResponseMessage(this.httpContext, {
statusCode: 201,
headers: {
location
}
});
}
public noContent() {
return new HttpResponseMessage(this.httpContext, {
statusCode: 204
});
}
public redirect(location) {
return new HttpResponseMessage(this.httpContext, {
statusCode: 302,
headers: {
location
}
});
}
}
export interface IHttpResponseMessageConstructorOptions {
content?: any;
headers?: {
[key: string]: string;
},
statusCode: number;
}
export class HttpResponseMessage {
public readonly content: any;
public readonly statusCode: number;
public readonly headers: {
[key: string]: string;
};
constructor(httpContext: interfaces.HttpContext, props: IHttpResponseMessageConstructorOptions) {
const handler = function() {
httpContext.response.status(props.statusCode);
if (handler.headers) {
for (const key of Object.keys(handler.headers)) {
httpContext.response.setHeader(key, handler.headers[key]);
}
}
if (handler.content !== undefined) {
httpContext.response.send(handler.content);
} else if (handler.statusCode === 302) {
httpContext.response.redirect(handler.headers.location);
} else {
httpContext.response.send();
}
} as any;
handler.content = props.content || undefined;
handler.statusCode = props.statusCode;
handler.headers = props.headers || {};
return handler as HttpResponseMessage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment