diff --git a/README.md b/README.md index 8372647..97d3298 100644 --- a/README.md +++ b/README.md @@ -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" +}); ``` diff --git a/index.js b/index.js index b3f1281..8f8ce21 100644 --- a/index.js +++ b/index.js @@ -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, };