Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add service to connect to web api #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,9 @@
"onchange": "^5.1.3",
"webpack": "^4.26.1",
"webpack-cli": "^3.1.2"
},
"dependencies": {
"ky": "^0.5.1",
"whatwg-fetch": "^3.0.0"
}
}
20 changes: 20 additions & 0 deletions src/rosetta-service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// This is a polyfill to use window.fetch on older browsers
import 'whatwg-fetch';
import ky from 'ky';
import nestify from './utils/nestify';

const rosettaService = (id = '', { prefixUrl = '' }) => {
const api = ky.extend({ prefixUrl });

return {
getNames: (culture = [], names = []) => api.get(`${id}/names`, {
searchParams: {
names: names.toString(),
culture: culture.toString(),
},
}).then(data => nestify(data)),
getCultures: () => api.get(`${id}/cultures`),
};
};

module.exports = rosettaService;
3 changes: 3 additions & 0 deletions src/utils/is-plain-object.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default t => !!t
&& (typeof t === 'object')
&& Object.prototype.toString.call(t) === '[object Object]';
24 changes: 24 additions & 0 deletions src/utils/nestify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import isObject from './is-plain-object';

const nestify = (obj, context = {}) => Object.keys(obj)
.reduce((baseObj, key) => {
const [thisKey, ...otherKeys] = key.split('.');
const keysToBeNested = otherKeys.join('.');
const originalValue = obj[key];
const shouldReturnSame = !keysToBeNested && !isObject(originalValue);

const objToNest = keysToBeNested
? { [keysToBeNested]: originalValue }
: originalValue;

const nestifiedObj = shouldReturnSame
? { [key]: originalValue }
: { [thisKey]: nestify(objToNest, baseObj[thisKey]) };

return {
...baseObj,
...nestifiedObj,
};
}, context);

export default nestify;