Last active
March 25, 2020 17:07
-
-
Save ajmas/53428a01d1ff6de6c0d86745b11b9012 to your computer and use it in GitHub Desktop.
Various HTTP related utilities in node js, specifically in Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Request } from 'express'; | |
function isTrue(value) { | |
return ['1', 1, 'yes', 'true', 'on'].indexOf(value) > -1; | |
} | |
function booleanValue(value) { | |
if (value) { | |
return ['1', 1, 'yes', 'true', 'on'].indexOf(value) > -1; | |
} | |
return undefined; | |
} | |
function getBaseUrl(req: Request) { | |
let proto = req.headers['x-forwarded-proto'] || req.protocol; | |
if (proto && Array.isArray(proto)) { | |
proto = proto[0]; | |
} | |
let host = req.headers['x-forwarded-host'] || req.get('host'); | |
if (host && Array.isArray(host)) { | |
host = host[0]; | |
} | |
let url = proto + '://' + host; | |
let port = req.get('port'); | |
if (port) { | |
url += ':' + port; | |
} | |
return url; | |
} | |
function getRemoteHost(req: Request) { | |
return req.headers['x-forwarded-for'] || req.connection.remoteAddress; | |
} | |
export { | |
isTrue, | |
booleanValue, | |
isRefererSameSite, | |
getBaseUrl, | |
getRemoteHost | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment