Skip to content

Commit

Permalink
Use config-object instead of enivronment variables
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Robsahm committed Dec 5, 2016
1 parent 6d31a8a commit 4095ed2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 31 deletions.
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
# Next Config Client

## Setup
Create the following enviroment variables
* Set CONFIG_REQUEST_URL to the url of your config server, ws://example.com/api/vx/config/
* Set CONFIG_REQUEST_INTERVAL in milliseconds

Initiate config fetching. `environment` is one of "dev", "stage" or "prod"
```
var refreshConfig = require("next-config-client");
refreshConfig(enviroment);
refreshConfig({
requestUrl: "ws://example.com/api/vx/config/",
environment: "dev"
});
```
43 changes: 17 additions & 26 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,62 +1,53 @@
const ws = require("ws");
const url = require("url");

if(!process.env.CONFIG_REQUEST_URL || !process.env.CONFIG_REQUEST_INTERVAL) {
console.error("Environment variables CONFIG_REQUEST_URL and CONFIG_REQUEST_INTERVAL must be set");
}

let config;

const requestConfig = (webSocket, environment) => {
webSocket.send(environment);
};

const initializeConfigUpdate = (environment) => {
const initializeConfigUpdate = (conf) => {
let config = {}
let retryNumOfTimes = 0;
let interval;
let intervalRef;

const connect = (resolve, reject) => {
const webSocket = new ws(url.resolve(process.env.CONFIG_REQUEST_URL, environment));
const webSocket = new ws(url.resolve(conf.requestUrl, conf.environment));

webSocket.on("open", () => {
retryNumOfTimes = 0;
requestConfig(webSocket, environment);
interval = setInterval(
requestConfig(webSocket, conf.environment);
intervalRef = setInterval(
requestConfig,
process.env.CONFIG_REQUEST_INTERVAL,
conf.interval,
webSocket,
environment
conf.environment
);
});

webSocket.on("message", (message) => {
config = JSON.parse(message);
webSocket.once("message", (message) => {
Object.assign(config, JSON.parse(message));
resolve(config);
});

webSocket.on("message", (message) => {
Object.assign(config, JSON.parse(message));
});

webSocket.on("error", (error) => {
console.error(error);
});

webSocket.on("close", () => {
clearInterval(interval);
clearInterval(intervalRef);
setTimeout(connect, Math.ceil(Math.pow(Math.E, retryNumOfTimes)) * 100, resolve, reject);
retryNumOfTimes += 1;
});
};

return new Promise((resolve, reject) => connect(resolve, reject));
return new Promise(connect);
};

const getConfig = () => {
if (!config) {
console.error("Config update not initialized! Use initializeConfigUpdate()");
}

return config;
}

module.exports = {
initializeConfigUpdate,
getConfig
config,
};

0 comments on commit 4095ed2

Please sign in to comment.