Skip to content

Commit

Permalink
feat(rest api) Refactor rest api architecture + add dns lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
tlgman committed Jun 16, 2019
1 parent 2322c14 commit f6ca58d
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 86 deletions.
88 changes: 4 additions & 84 deletions gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,92 +6,12 @@

// You can delete this file if you're not using it
const path = require(`path`)
const https = require(`https`);
const _ = require(`lodash`);
// const dns = require(`dns`);


function getTranspilersFromParams(params) {
const transpilerParams = params.transpiler ? params.transpiler.split(',') : [];
const transpilers = [];
if(transpilerParams.includes('babel')) {
transpilers.push('babel');
}
if(transpilerParams.includes('typescript')) {
transpilers.push('typescript');
}
if(!transpilers.length && params.mainLibrary === 'react') {
transpilers.push('babel');
}
return transpilers;
}

function getOptimizationFromParams(params, transpilers) {
const optiParams = params.optimization ? params.optimization.split(',') : [];
const optis = [];
if(optiParams.includes('code-split-vendors')) {
optis.push('code-split-vendors');
}
if(optiParams.includes('react-hot-loader') && params.mainLibrary === 'react' && !transpilers.includes('typescript')) {
optis.push('react-hot-loader');
}
return optis;
}

function getValuesFromParamsAvailables(param, availableParams) {
const valuesParam = param ? param.split(',') : null;
if(!valuesParam) {
return [];
}
return availableParams.filter((availableParam) => valuesParam.includes(availableParam));
}
const RestAPI = require(`./src/api/RestAPI`);

exports.onCreateDevServer = ({ app }) => {

// let opt = {host: 'https://s3-qsfdsqfsqfdseu-west-1.amazonaws.com/jakoblind/zips-webpack/'};
// dns.lookup(opt.host, function (err, addr) {
// if (err) {
// // err code
// } else {
// // patches in the host header in order to please the HTTP/1.1 servers aka most of them
// opt.headers.host = opt.host;
// // makes the connection to the resolved address itself
// opt.host = addr;
// var req = https.request(opt);
// // [...]
// }
// });

app.get('/api/webpack/', function (req, res) {
const baseUrl = 'https://s3-eu-west-1.amazonaws.com/jakoblind/zips-webpack/';
// TODO rajouter _.default ==> if transpilers is undefined => error
const params = _.mapValues(req.query, (value) => typeof value === 'string' ? value.toLowerCase() : '');

let baseProjectLib = (params.mainLibrary === 'react' || params.mainLibrary === 'vue') ? params.mainLibrary : '';

const transpilers = getTranspilersFromParams(params);
const styling = getValuesFromParamsAvailables(params.styling, ['css', 'css-modules', 'sass', 'less']);
const images = getValuesFromParamsAvailables(params.image, ['svg', 'png']);
const utilities = getValuesFromParamsAvailables(params.utilities, ['lodash', 'moment']);
const optimizations = getOptimizationFromParams(params, transpilers);

const features = _.concat(_.sortBy(_.concat(transpilers, styling, images, optimizations, baseProjectLib)), utilities);
const filename = `empty-project-${ _.kebabCase(features)}.zip`;

let url = `${baseUrl}${filename}`;
console.log('URL: ', url);
res.send(url);
https.get(url, function(resultFile) {
if(resultFile.statusCode !== 200) {
res.status(404);
return;
}
res.setHeader('Content-Type','application/zip');
res.setHeader('Content-Disposition',`attachment; filename=${filename}`);
resultFile.pipe(res);
});
})
}
const restAPI = new RestAPI();
restAPI.init(app);
};

exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
Expand Down
56 changes: 56 additions & 0 deletions src/api/RestAPI.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const https = require('https');
const dns = require( 'dns');
const _ = require('lodash');
const RestAPIUtils = require('../utils/RestAPIUtils');

const DOWNLOAD_PROEJECT_DOMAIN = 's3-eu-west-1.amazonaws.com';
const BASE_DOWNLOAD_PROJECT_WEBPACK_URL = `https://${DOWNLOAD_PROEJECT_DOMAIN}/jakoblind/zips-webpack/`;

class RestAPI {
init(app) {
this.checkDnsAccessibility();
app.get('/api/webpack/', this.getProject.bind(this));
}

getProject(req, res) {
if(!this.isAccessibleDomain) {
res.status(503).send('Resource unreachable');
return;
}

const params = _.mapValues(req.query, (value) => typeof value === 'string' ? value.toLowerCase() : '');
const baseProjectLib = (params['main-library'] === 'react' || params['main-library'] === 'vue') ? params['main-library'] : '';
const transpilers = RestAPIUtils.getTranspilersFromParams(params);
const styling = RestAPIUtils.getAvailablesValuesFromParams(params.styling, ['css', 'css-modules', 'sass', 'less']);
const images = RestAPIUtils.getAvailablesValuesFromParams(params.image, ['svg', 'png']);
const utilities = RestAPIUtils.getAvailablesValuesFromParams(params.utilities, ['lodash', 'moment']);
const optimizations = RestAPIUtils.getOptimizationFromParams(params, transpilers);

const features = _.concat(_.sortBy(_.concat(transpilers, styling, images, optimizations, baseProjectLib)), utilities);
const filename = `empty-project-${ _.kebabCase(features)}.zip`;

const url = `${BASE_DOWNLOAD_PROJECT_WEBPACK_URL}${filename}`;
https.get(url, function(resultFile) {
if(resultFile.statusCode !== 200) {
res.status(404).send('File not found');
return;
}
res.setHeader('Content-Type','application/zip');
res.setHeader('Content-Disposition',`attachment; filename=${filename}`);
resultFile.pipe(res);
});
}

checkDnsAccessibility() {
dns.lookup(DOWNLOAD_PROEJECT_DOMAIN, (err) => {
if (err) {
this.isAccessibleDomain = false;
console.error(`Domain ${DOWNLOAD_PROEJECT_DOMAIN} is unreachable`);
return;
}
this.isAccessibleDomain = true;
})
}
}

module.exports = RestAPI;
2 changes: 0 additions & 2 deletions src/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -375,8 +375,6 @@ function Configurator(props) {
const isTypescript = _.includes(selectedArray, 'Typescript')

const projectname = getDefaultProjectName('empty-project', selectedArray)
console.log('Selected array: ', selectedArray);
console.log('Project name: ', projectname);

const {
featureConfig,
Expand Down
39 changes: 39 additions & 0 deletions src/utils/RestAPIUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

class RestAPIUtils {
static getTranspilersFromParams(params) {
const transpilerParams = params.transpiler ? params.transpiler.split(',') : [];
const transpilers = [];
if(transpilerParams.includes('babel')) {
transpilers.push('babel');
}
if(transpilerParams.includes('typescript')) {
transpilers.push('typescript');
}
if(!transpilers.length && params['main-library'] === 'react') {
transpilers.push('babel');
}
return transpilers;
}

static getOptimizationFromParams(params, transpilers) {
const optiParams = params.optimization ? params.optimization.split(',') : [];
const optis = [];
if(optiParams.includes('code-split-vendors')) {
optis.push('code-split-vendors');
}
if(optiParams.includes('react-hot-loader') && params['main-library'] === 'react' && !transpilers.includes('typescript')) {
optis.push('react-hot-loader');
}
return optis;
}

static getAvailablesValuesFromParams(param, availableValues) {
const valuesParam = param ? param.split(',') : null;
if(!valuesParam) {
return [];
}
return availableValues.filter((availableParam) => valuesParam.includes(availableParam));
}
}

module.exports = RestAPIUtils;

0 comments on commit f6ca58d

Please sign in to comment.