Skip to content
This repository has been archived by the owner on Apr 17, 2020. It is now read-only.

Commit

Permalink
feat(core): refactor and update document to apis version 2
Browse files Browse the repository at this point in the history
  • Loading branch information
Kamontat Chantrachirathumrong committed Dec 28, 2018
1 parent fe94bae commit bb09093
Show file tree
Hide file tree
Showing 16 changed files with 229 additions and 275 deletions.
16 changes: 16 additions & 0 deletions 404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Page not Found</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>

<body>
<div>
<h1>Page not found, sorry.</h1>
<h4>Kamontat Chantrachirathumrong</h4>
</div>
</body>
</html>
6 changes: 5 additions & 1 deletion _redirects
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
# /* /.netlify/functions/:splat 200!

# redirect to docs
/ /docs 200!

# redirect netlify function path
/* /.netlify/functions/:splat 200!
/latest/* /.netlify/functions/:splat 200!
/v2/* /.netlify/functions/:splat 200!
27 changes: 0 additions & 27 deletions lib/analysic.js

This file was deleted.

31 changes: 0 additions & 31 deletions lib/content.js

This file was deleted.

53 changes: 53 additions & 0 deletions lib/ghApi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const Octokit = require("@octokit/rest");
const Promise = require("bluebird");

import {
Information,
FetchUrl
} from "./ghLink";

export class GHAPIs {
_octokit = undefined;

constructor(event) {
this._octokit = new Octokit({
headers: {
authorization: event.headers.authorization
}
});
}

queryAll(types, opts = {}) {
return Promise.reduce(types, (p, c) => {
return this.queryOnce(c, opts).then(res => {
p[c] = res;
return p
})
}, {})
}

queryOnce(type, opts = {}) {
return this.queryFileList(opts.user, type, opts).then(files => {
return Promise.all(files.map(url => FetchUrl(url)))
})
}

queryFileList(user, folder, opts = {}) {
const filter = opts.filter || '.json';
const path = `static/resources/${user}/${folder}`;

return this._octokit.repos.getContents({
owner: Information.owner,
repo: Information.repo,
path,
ref: opts.branch || Information.branch
}).then(result => {
const data = result.data || result;

return data.reduce((p, c) => {
if (c.name.includes(filter)) p.push(c.download_url);
return p;
}, []);
})
}
}
13 changes: 13 additions & 0 deletions lib/ghLink.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const axios = require("axios")

const repo_owner = "kcnt-info";
const repo_name = "website";
const branch = "master";
Expand All @@ -9,6 +11,17 @@ export const Information = {
branch: branch
};

/**
* Fetch url power by axios
* @param {String} url path to query
* @param {Object} opts options
* @param {Boolean} opts.all return all object from axios, otherwise return only data
* @param {Object} opts.axiosOptions option parsing to axios get method
*/
export const FetchUrl = (url, opts = {}) => {
return axios.get(url, opts.axiosOptions).then(v => opts.all ? v : v.data)
}

/**
* generate github link to query result
* @param {String} path path from root folder
Expand Down
26 changes: 24 additions & 2 deletions lib/parseUrl.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,27 @@ const matchPath = (path, results) => {
return results[index]
}

const matchesPath = (path, results) => {
return results.filter(p => path.includes(`/${p}`))
}

const matchQuery = (query, options) => {
if (options === undefined) return query;
return options.includes(query) ? query : undefined
}

const matchesQuery = (query, options) => {
if (options === undefined) return [query];
if (query === undefined) return [];

return options.filter(p => query.includes(p))
}

/**
*
* @param {String} name name of the key result and query name
* @param {Array<String>} options possible values
* @param {String} defaultValue default value if value is not exist
* @param {String|Array<String>} defaultValue default value if value is not exist
*/
export const GenObj = (name, options,
defaultValue = undefined) => {
Expand All @@ -33,7 +44,18 @@ export const ParseParameters = (event, ...obj) => {
const path = event.path;
const result = {};
obj.forEach(v => {
result[v.name] = matchPath(path, v.options) || matchQuery(query[v.name], v.options) || v.default
if (Array.isArray(v.default)) {
if (result[v.name] === undefined) result[v.name] = [];

const _paths = matchesPath(path, v.options)
const _params = matchesQuery(query[v.name], v.options)

if (_paths.length > 0) result[v.name].push(..._paths)
else if (_params.length > 0) result[v.name].push(..._params)
else if (v.default.length > 0) result[v.name].push(...v.default)
} else {
result[v.name] = matchPath(path, v.options) || matchQuery(query[v.name], v.options) || v.default
}
})
return result
}
9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
"license": "MIT",
"dependencies": {
"@octokit/rest": "16.2.0",
"aglio": "^2.3.0",
"axios": "0.18.0"
"aglio": "2.3.0",
"axios": "0.18.0",
"bluebird": "3.5.3"
},
"devDependencies": {
"apidoc": "0.17.7",
Expand All @@ -17,8 +18,8 @@
"scripts": {
"start": "netlify-lambda serve src/apis",
"build": "netlify-lambda build src/apis",
"docs:compile": "mkdir docs 2>/dev/null; aglio --theme-variables slate -i src/docs/index.apib -o docs/index.html && cp _redirects docs/_redirects",
"docs:start": "aglio --theme-variables slate -i src/docs/index.apib -o docs/index.html -s",
"docs:compile": "mkdir docs 2>/dev/null; aglio --theme-variables slate -i src/docs/index.apib -o docs/docs.html && cp _redirects docs/_redirects && cp 404.html docs/404.html",
"docs:start": "aglio --theme-variables slate -i src/docs/index.apib -o docs/docs.html -s",
"deploy": "yarn docs:compile && yarn build"
},
"apidoc": {
Expand Down
88 changes: 56 additions & 32 deletions src/apis/collection.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// const axios = require("axios");
const Octokit = require("@octokit/rest");
const {
ParseParameters,
GenObj
} = require('../../lib/parseUrl')

// const { PersonalInformationLink, PersonalSocialLink } = require("../lib/link");
const { AnalysicEvent, defaultUser, defaultUsers } = require("../../lib/analysic");
const { QueryContent, TransformResult, MultipleQueryResult } = require("../../lib/content");
const {
GHAPIs
} = require('../../lib/ghApi')

const query = async (octokit, key, user) => {
const raw = await QueryContent(octokit, user, key);
Expand All @@ -14,32 +16,26 @@ const query = async (octokit, key, user) => {
return json;
};

exports.handler = function(event, context, callback) {
const octokit = new Octokit({
headers: { authorization: event.headers.authorization }
});

const params = AnalysicEvent(event, defaultUser, defaultUsers, "projects", [
"educations",
"interests",
"languages",
"projects",
"references",
"skills",
"volunteers",
"works"
]);

(async () => {
// TODO: implement performance here
const result = await Promise.all(params.types.map(async type => await query(octokit, type, params.user)));
return result.reduce((p, c) => {
const key = Object.keys(c)[0];
p[key] = c[key];
return p;
}, {});
})()
.then(v => {
exports.handler = function (event, context, callback) {
const result = ParseParameters(event,
GenObj("user", ["net", "prang"]),
GenObj("branch", ["master", "dev"]),
GenObj("lang", ["en", "th"]),
GenObj("type", [
"educations",
"interests",
"languages",
"projects",
"references",
"skills",
"volunteers",
"works"
], ["projects"]));

console.log(result);
const apis = new GHAPIs(event);

apis.queryAll(result.type, result).then(v => {
callback(undefined, {
statusCode: 200,
headers: {
Expand All @@ -51,4 +47,32 @@ exports.handler = function(event, context, callback) {
});
})
.catch(callback);
};

// const octokit = new Octokit({
// headers: {
// authorization: event.headers.authorization
// }
// });

// (async () => {
// // TODO: implement performance here
// const response = await Promise.all(result.type.map(async type => await query(octokit, type, result.user)));
// return response.reduce((p, c) => {
// const key = Object.keys(c)[0];
// p[key] = c[key];
// return p;
// }, {});
// })()
// .then(v => {
// callback(undefined, {
// statusCode: 200,
// headers: {
// "Content-Type": "application/json",
// "Access-Control-Allow-Origin": "*",
// "Access-Control-Allow-Headers": "*"
// },
// body: JSON.stringify(v)
// });
// })
// .catch(callback);
};
16 changes: 8 additions & 8 deletions src/apis/logo.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
const axios = require("axios")

const {
ParseParameters,
GenObj
} = require('../../lib/parseUrl')

const {
FetchUrl,
LogoLink
} = require("../../lib/ghLink");

exports.handler = function (event, context, callback) {
const result = ParseParameters(event,
GenObj("branch", ["master", "dev"]),
GenObj("color", ["primary", "light", "dark"]),
GenObj("size", ["normal", "smaller", "high"]),
GenObj("size", ["normal", "small", "high"]),
GenObj("type", ["normal", "round"]),
GenObj("extension", ["png", "svg"]))

const url = LogoLink(result.color, result);

axios
.get(url, {
responseType: 'arraybuffer'
})
.then(response => {
FetchUrl(url, {
axiosOptions: {
responseType: 'arraybuffer'
},
all: true
}).then(response => {
let image = Buffer.from(response.data, 'binary').toString('base64')

callback(undefined, {
Expand Down
Loading

0 comments on commit bb09093

Please sign in to comment.