Skip to content
This repository has been archived by the owner on Oct 15, 2022. It is now read-only.

Commit

Permalink
Successful request get! Now to implement other methods.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jonathan Ling committed Sep 28, 2018
1 parent 3d554e6 commit 8a2d2d3
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 11 deletions.
34 changes: 34 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,39 @@
# NOTE: Uppercase values are expected for the non customizable portions of the environment properties.
# You can replace 'SOME_SERVICE' with whatever you like (e.g. BEANS) and then go to https://<server-url>/BEANS to kick off the request process.

# Key defines a route to send a request off somewhere else. Value defines the values to pull in from ENV and send with the request.
SOME_SERVICE=SOME_SERVICE_CLIENT_ID,SOME_SERVICE_API_TOKEN

# URL to send the proxied request to.
SOME_SERVICE_URL='https://api.someservice.tv/users'

# The root property you want the proxy to return from a successful call.
SOME_SERVICE_ROOT_PROP=data

# Key you want to use in your request.
SOME_SERVICE_CLIENT_ID_KEY=Client-ID

# The value assigned to the previous key variable.
SOME_SERVICE_CLIENT_ID_VALUE=somevalue

# The type of property: possible values are isHeader, isRequestProp, isQueryStr. Note that this is required.
# isHeader = header property
# isRequestProp = json body property
# isQueryStr = query string property
SOME_SERVICE_CLIENT_ID_OPTS=isHeader

SOME_SERVICE_API_TOKEN_KEY=jwt
SOME_SERVICE_API_TOKEN_VALUE=someothervalue
SOME_SERVICE_API_TOKEN_OPTS=isRequestProp

# HTTP port to start the server on
PORT=3000

# Cookie secret to sign cookies from the server.
COOKIE_SECRET=VEhJUyBJUyBBIFNFQ1JFVCBZT1UgQkFTVEFSRC4=

# CORS toggle switch to turn CORS on or off. Delete or comment to turn off.
CORS_ENABLED=true

# CORS whitelist for your domains. This is maybe how CORS works...
WHITELIST="https://codepen.io/,https://myblog.com/,https://myghpage.github.io/"
62 changes: 52 additions & 10 deletions src/Routes/ProxyRoute.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import axios, { AxiosRequestConfig } from "axios";
import { NextFunction, Request, Response, Router } from "express";
import http from "http";
import https from "https";

export default class ProxyRoute {

Expand All @@ -8,26 +11,65 @@ export default class ProxyRoute {
});
}

private static readonly RootAxiosConfig: AxiosRequestConfig = {
baseURL: "",
headers: {},
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
maxContentLength: 2000,
maxRedirects: 5,
method: "GET",
params: {},
proxy: false,
responseType: "json",
timeout: 1000,
transformResponse: [],
url: "",
validateStatus: (status) => {
return status >= 200 && status < 400;
},
withCredentials: false,
};

private static readonly PostConfig: AxiosRequestConfig = {
data: {},
method: "POST",
};

private async index(req: Request, res: Response, next: NextFunction) {
const appName: string = req.params.appName;
// Extract the particulars from the env file.
const envForApp: object = this.getEnvForApp(appName);

// Proxy the request.
res.json({
data: envForApp,
});
const remoteRes = await this.getResponse(req, envForApp);

res.json(remoteRes);
}

private getEnvForApp(appName: string): object {
private async getResponse(req: Request, envForApp: any): Promise<any> {
const reqConfig = Object.assign(ProxyRoute.RootAxiosConfig, envForApp);
const remoteRes: any = await axios(reqConfig);
return remoteRes[envForApp.rootProp];
}
private getEnvForApp(appName: string): any {
const envStrsForApp = process.env[appName].split(",");
const envForApp: any = {};
const envForApp: any = Object.assign(ProxyRoute.RootAxiosConfig, {
rootProp: process.env[appName + "_ROOT_PROP"],
url: process.env[appName + "_URL"],
});
// console.dir(process.env); // tslint:disable-line no-console
envStrsForApp.forEach((value) => {
const processEnvKey = process.env[value + "_KEY"] ;
const processEnvVal = process.env[value + "_VALUE"];
// const processEnvOpts = process.env[value + "_OPTS"]; // contemplating this one
envForApp[processEnvKey] = processEnvVal;
envStrsForApp.forEach((envStr) => {
const processEnvKey = process.env[envStr + "_KEY"] ;
const processEnvVal = process.env[envStr + "_VALUE"];
const processEnvOpts = process.env[envStr + "_OPTS"]; // contemplating this one
if (processEnvOpts.includes("isHeader")) {
envForApp.headers[processEnvKey] = processEnvVal;
} else if (processEnvOpts.includes("isRequestProp")) {
envForApp.data[processEnvKey] = processEnvVal;
} else if (processEnvOpts.includes("isQueryStr")) {
envForApp.params[processEnvKey] = processEnvVal;
}
});
return envForApp;
}
Expand Down
20 changes: 19 additions & 1 deletion src/Server/Server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import cors from "cors";
import dotenv from "dotenv";
import errorHandler = require("errorhandler");
import Express from "Express";
Expand Down Expand Up @@ -66,13 +67,15 @@ export default class Server {
* @method config
*/
public config() {
const isDevelopment = process.env.NODE_ENV;
// get environment variables into node process
dotenv.config();
// use logger middlware
this.app.use(logger("dev"));
if (isDevelopment) { this.app.use(logger("dev")); }

// use json form parser middleware
this.app.use(bodyParser.json());
this.app.set("json spaces", isDevelopment ? 4 : 0);

// use query string parser middlware
this.app.use(bodyParser.urlencoded({
Expand All @@ -81,6 +84,21 @@ export default class Server {

// use cookie parser middleware
this.app.use(cookieParser(process.env.COOKIE_SECRET));
// whitelist domains from env file
if (process.env.CORS_ENABLED) {
const whitelist = process.env.WHITELIST.split(",");
const corsOpts = {
origin: (origin: any, callback: (err: Error | any, arg2?: any) => void) => {
console.log(origin); // tslint:disable-line no-console
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
};
this.app.use(cors(corsOpts));
}

// use override middlware
this.app.use(methodOverride());
Expand Down

0 comments on commit 8a2d2d3

Please sign in to comment.