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

Commit

Permalink
🎨 Implement API repo (Gum-Joe/bedel-api)
Browse files Browse the repository at this point in the history
🎨 Implement API repo (Gum-Joe/bedel-api)
🚀 Change latest preset for babel to env
🎨 Move creation of server below db connect
🚑 Fix an issue where prefixes would clash for logger and API
🎨 🚀 Added a loader to update bedel-api, so we don't have to
manually update it everytime we update the API on GitHub
🎨 Streamlined boot loader api to use async.series() from async
module and direcly take and execute callback, so that the loaders finish
before the server loads
💻 Added cli options to skip and force API update
📦 Updated dependencies (too many to list). Semantic rebuilt
🚑 Fix an issue where certain image-webpack-loader options were
causing warnings
  • Loading branch information
Gum-Joe committed Mar 25, 2017
1 parent c577da5 commit 616556d
Show file tree
Hide file tree
Showing 33 changed files with 3,201 additions and 884 deletions.
2 changes: 1 addition & 1 deletion .babelrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
"plugins": [
"react-hot-loader/babel"
],
"presets": ["latest", "stage-0", "react"]
"presets": ["env", "stage-0", "react"]
}
14 changes: 7 additions & 7 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
/**
* Module depedencies
*/
const { API } = require('./app/api');
const { ServerAPI } = require('bedel-api/api/server');
const appLoader = require('./app/apps/loader');
const bodyParser = require('body-parser');
const chalk = require('chalk');
Expand Down Expand Up @@ -134,19 +134,19 @@ module.exports = (options) => {
app.use('/', routes.index);
app.use('/api', routes.api);

// Connect to db
db.connect(options);

// Create server and listen
logger.debug('Creating server...');
const server = http.createServer(app);
server.listen(PORT, () => {
logger.info(`Listenning on port ${PORT}.`);
});

// Connect to db
db.connect(options);

// Init the api
const api = new API(server, app, options);
helpers.addApiPlugins(api);
// TODO: New API migrations
const api = new ServerAPI(logger, server, app /*, options*/);
//helpers.addApiPlugins(api);

// Load apps
appLoader(api, logger);
Expand Down
2 changes: 2 additions & 0 deletions app/apps/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const Logger = require('../util/logger');
const { join } = require('path');

module.exports = (api, logger) => {
// Fix logger prefix clashes
delete logger.prefix;
logger.debug("Loading apps...");
App.find({}, (err, apps) => {
if (err) {
Expand Down
107 changes: 107 additions & 0 deletions app/boot/bedel-api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*eslint no-extend-native: "off"*/
// Loader responsible for updating api
// FOR DEV ONLY
// NOTE: REMOVE IN FINAL RELEASE

/**
* Module dependencies
*/
const request = require('request');
const api_package_json = require('bedel-api/package.json');
const chalk = require('chalk');
const { spawn } = require('child_process');
const which = require('which');
const BEDEL_API_OWNER = "Gum-Joe";
const BEDEL_API_REPO = "bedel-api";
const BEDEL_API_USER_AGENT = "bedel-server";
const BEDEL_INSTALL_API = `git://github.com/${BEDEL_API_OWNER}/${BEDEL_API_REPO}`;

// Replace method
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};

module.exports = (args, logger, done) => {
if (process.env.NODE_ENV === "production" || args["skip_api_update"]) {
// Dosn't need updating
logger.debug("Not updating API");
done();
} else {
logger.info("Checking for API updates...");
logger.info("To skip updating, use the --skip-api-update flag.");
logger.info("To force updating, use the --force-api-update flag.");
// Check for updates
request({
url: `https://api.github.com/repos/${BEDEL_API_OWNER}/${BEDEL_API_REPO}/commits`,
headers: {
"User-Agent": BEDEL_API_USER_AGENT
}
}, (err, res, body) => {
if (err) {
// Err getting SHA (internal)
logger.err(err.message);
logger.err(err.code);
logger.warn("Could not update API");
logger.warn("You may need to update it yourself");
logger.warn(" https://github.com/Gum-Joe/bedel/README.md");
done();
} else if (res.statusCode > 300) {
// Err getting SHA (response)
logger.err("Failed to complete api update request");
logger.err(` Got code ${chalk.cyan(`'${res.statusCode}'`)} from https://api.github.com/repos/${BEDEL_API_OWNER}/${BEDEL_API_REPO}/commits`);
logger.err(` Response: ${chalk.cyan(body)}`);
logger.warn("Could not update API");
logger.warn("You may need to update it yourself");
logger.warn(" https://github.com/Gum-Joe/bedel/README.md");
done();
} else {
// Check if update neede
logger.debug("Got commits from github repo for bedel api");
logger.debug("Parsing JSON...");
const commits = JSON.parse(body);
const currentAPI = commits[0];
logger.debug("Checking package.json api version...");
const apiInstalledVersion = api_package_json.gitHead;
if (currentAPI.sha !== apiInstalledVersion || args["force_api_update"]) {
// Update
logger.info("Updates to bedel api required!");
logger.info(`Current commit SHA: ${chalk.cyan(currentAPI.sha)}`);
logger.info(`Installed commit SHA: ${chalk.magenta(apiInstalledVersion)}`);
logger.info("Updating...");
const npmUpdate = spawn(which.sync("npm"), [
"install",
"--save",
BEDEL_INSTALL_API
]);
npmUpdate.stdout.on("data", (data) => {
data.toString('utf8')
.split("\n")
.forEach((value) => {
if (value.match(/[a-z]/i)) {
logger.info(value);
}
});
});
npmUpdate.stderr.on("data", (data) => {
data.toString('utf8').split("npm").forEach((value) => logger.warn("npm" + value.replaceAll("\n", "")));
});
npmUpdate.on("exit", (code) => {
if (code !== 0) {
logger.err("Error updating bedel api!");
logger.err(` Exit code: ${chalk.cyan(code)}`);
done();
} else {
logger.info("Update successful.");
done();
}
});
} else {
// Update not needed
logger.info("No update needed to bedel api.");
done();
}
}
});
}
};
32 changes: 20 additions & 12 deletions app/boot/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ const Logger = require('../util/logger');
//const prompt = require('./prompt');
const appLoader = require('./app-loader');
const https = require('./https');
const api = require('./bedel-api');
const async = require('async');

// Loaders
const loaders = [
//https,
//prompt, For later
api,
appLoader
];

Expand All @@ -20,18 +23,24 @@ const loaders = [
* @private
*/

function __boot(options) {
function __boot(options, cb) {
const logger = new Logger(options);
let asyncLoaders = [];
// Add callback as a loaders
loaders.push(function () {
cb();
});
let i = 0;
while (i < loaders.length) {
const loader = loaders[i];
loader(options, logger, (err) => {
i++;
if (err) {
logger.err(`Loader ${loaders[i]} failed`);
logger.throw(err);
}
});
while (i <= loaders.length) {
if (i < loaders.length) {
const loader = loaders[i];
asyncLoaders.push(function (done) {
loader(options, logger, done);
});
} else {
async.series(asyncLoaders);
}
i++;
}
}

Expand All @@ -55,6 +64,5 @@ const _boot = (resolve, reject) => {
};
// Export method
module.exports = (options, cb) => {
__boot(options);
cb();
__boot(options, cb);
};
4 changes: 3 additions & 1 deletion app/cli/commands/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ module.exports = (argv) => {
[ '-p, --port <port>', 'Specifies a port to open the server' ],
[ '--color', 'Use colour' ],
[ '--debug', 'Debug logging' ],
[ '--force-api-update', 'Force updating the api' ],
[ '--no-color', 'Don\'t use colour' ],
[ '--no-prompt', 'Don\'t use a prompt' ]
[ '--no-prompt', 'Don\'t use a prompt' ],
[ '--skip-api-update', 'Skip updating the api' ]
],
{
script: 'bedel-server',
Expand Down
Loading

0 comments on commit 616556d

Please sign in to comment.