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

Commit

Permalink
feat(apis): add personal api and collection api
Browse files Browse the repository at this point in the history
  • Loading branch information
Kamontat Chantrachirathumrong committed Dec 18, 2018
1 parent 5119ea0 commit fb8fb95
Show file tree
Hide file tree
Showing 10 changed files with 4,654 additions and 2 deletions.
Empty file added .functions/.gitkeep
Empty file.
142 changes: 142 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@

# Created by https://www.gitignore.io/api/node,macos,visualstudiocode,linux
# Edit at https://www.gitignore.io/?templates=node,macos,visualstudiocode,linux

### Linux ###
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*

### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# parcel-bundler cache (https://parceljs.org/)
.cache

# next.js build output
.next

# nuxt.js build output
.nuxt

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

#DynamoDB Local files
.dynamodb/

### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

### VisualStudioCode Patch ###
# Ignore all local history of files
.history

# End of https://www.gitignore.io/api/node,macos,visualstudiocode,linux

.functions
50 changes: 50 additions & 0 deletions apis/collection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// const axios = require("axios");
const Octokit = require("@octokit/rest");

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

const query = async (octokit, key, user) => {
const raw = await QueryContent(octokit, user, key);
const results = TransformResult(raw);

const json = {};
json[key] = await MultipleQueryResult(results);
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 => {
callback(undefined, {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(v)
});
})
.catch(callback);
};
35 changes: 35 additions & 0 deletions apis/personal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const axios = require("axios");

const { PersonalInformationLink, PersonalSocialLink } = require("../lib/link");
const { AnalysicEvent, defaultUser, defaultUsers } = require("../lib/analysic");

/**
* @api {get} /user/:id Request User information
* @apiName GetUser
* @apiGroup User
*
* @apiParam {Number} id Users unique ID.
*
* @apiSuccess {String} firstname Firstname of the User.
* @apiSuccess {String} lastname Lastname of the User.
*/
exports.handler = function(event, _, callback) {
const result = AnalysicEvent(event, defaultUser, defaultUsers, "information", ["information", "social"]);
console.log(result);

const url =
result.type === "social"
? PersonalSocialLink(result.user, { branch: result.branch })
: PersonalInformationLink(result.user, { branch: result.branch });

axios
.get(url)
.then(result => {
callback(undefined, {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(result.data)
});
})
.catch(callback);
};
27 changes: 27 additions & 0 deletions lib/analysic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
export const defaultUser = "net";
export const defaultUsers = ["net", "prang"];

export const AnalysicEvent = (event, defaultUser, users, defaultPath, paths, defaultBranch = "master") => {
let user = event.queryStringParameters.user || defaultUser;
let branch = event.queryStringParameters.branch || defaultBranch;
let type = event.queryStringParameters.type || defaultPath;
let types = [type];

const userIndex = users.findIndex(u => event.path.includes(`/${u}`));
if (userIndex >= 0) user = users[userIndex];

if (defaultPath) {
const matches = paths.filter(p => event.path.includes(`/${p}`));
if (matches && matches.length > 0) {
type = matches[0];
types = matches;
}
}

return {
user: user,
type: type,
types: types,
branch: branch
};
};
29 changes: 29 additions & 0 deletions lib/content.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const axios = require("axios");

const { Information } = require("../lib/link");

// return promise
export const QueryContent = (octokit, username, filename) => {
const path = `static/resources/${username}/${filename}`;

return octokit.repos.getContents({
owner: Information.owner,
repo: Information.repo,
path,
ref: Information.branch
});
};

export const TransformResult = result => {
const data = result.data || result;

return data.reduce((p, c) => {
if (c.name.includes(".json")) p.push(c.download_url);
return p;
}, []);
};

export const MultipleQueryResult = results => {
// TODO: implement performance here
return Promise.all(results.map(r => axios.get(r).then(v => v.data)));
};
22 changes: 22 additions & 0 deletions lib/link.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const repo_owner = "kcnt-info";
const repo_name = "website";
const branch = "master";

export const Information = {
owner: repo_owner,
repo: repo_name,
branch: branch
};

export const generateLink = (username, path, opts = {}) => {
return `https://raw.githubusercontent.com/${repo_owner}/${repo_name}/${opts.branch ||
branch}/static/resources/${username}/${path}`;
};

export const PersonalInformationLink = (user, opts = {}) => {
return generateLink(user, "personal/information.json", opts);
};

export const PersonalSocialLink = (user, opts = {}) => {
return generateLink(user, "personal/social.json", opts);
};
2 changes: 1 addition & 1 deletion netlify.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[build]
functions = "apis"
functions = ".functions"
[build.environment]
YARN_VERSION = "1.3.2"
YARN_FLAGS = "--no-ignore-optional"
14 changes: 13 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,17 @@
"description": "My Portfolio website",
"repository": "https://github.com/kcnt-info/apis.git",
"author": "Kamontat Chantrachirathumrong <kamontat_c@hotmail.com>",
"license": "MIT"
"license": "MIT",
"dependencies": {
"@octokit/rest": "16.2.0",
"axios": "0.18.0"
},
"devDependencies": {
"apidoc": "0.17.7",
"netlify-lambda": "1.1.1"
},
"scripts": {
"start": "netlify-lambda serve apis",
"docs": "yarn apidoc -i apis -o docs --verbose"
}
}
Loading

0 comments on commit fb8fb95

Please sign in to comment.