Skip to content

refactor: rewrite proxy <=> client internals #771

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

Merged
merged 1 commit into from
Apr 15, 2018
Merged
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
189 changes: 123 additions & 66 deletions src/api/client.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
// @flow

import { Schema } from 'normalizr';
import { merge } from 'lodash';
import { version } from 'package.json';
import { Platform } from 'react-native';

import Schemas from './schemas';

type SpecialParameters = {
forceRefresh?: boolean,
loadMore?: boolean,
perPage?: number,
};

type FetchParameters = {
method?: string,
headers?: Object,
body?: Object,
};

export type CallParameters = {
endpoint: string,
schema: Schema,
params: SpecialParameters,
fetchParameters?: FetchParameters,
normalizrKey?: string,
paginationArgs?: Array<string | number | boolean>,
entityId?: String | number,
};

export type CallType = CallParameters & {
type: string,
};

export class Client {
API_ROOT = 'https://api.github.com/';

Expand All @@ -17,62 +50,81 @@ export class Client {
POST: 'POST',
};

Accept = {
DIFF: 'application/vnd.github.v3.diff+json',
FULL: 'application/vnd.github.v3.full+json',
HTML: 'application/vnd.github.v3.html+json',
JSON: 'application/vnd.github.v3+json',
MERCY_PREVIEW: 'application/vnd.github.mercy-preview+json',
RAW: 'application/vnd.github.v3.raw+json',
};

authHeaders = {};

call = async (
url,
params = {},
{ method = this.Method.GET, body = {}, headers = {} } = {}
url: string,
params: SpecialParameters = {},
fetchParameters: FetchParameters = {}
) => {
let finalUrl;

if (params.url) {
// a different url was provided, use it instead (paginated)
finalUrl = params.url;
} else {
finalUrl = url;
// add explicitely specified parameters
if (params.per_page) {
finalUrl = `${finalUrl}${finalUrl.includes('?') ? '&' : '?'}per_page=${
params.per_page
}`;
}
let finalUrl = url;

// add explicitely specified parameters
if (params.perPage) {
finalUrl = `${finalUrl}${
finalUrl.includes('?') ? '&' : '?'
}per_page=${Number(params.perPage).toString()}`;
}

if (!finalUrl.includes(this.API_ROOT)) {
finalUrl = `${this.API_ROOT}${finalUrl}`;
}

const parameters = {
const { method, headers, body } = fetchParameters;

const parameters: any = {
method,
headers: {
'User-Agent': `GitPoint/${version} ${Platform.OS}`,
'Cache-Control': 'no-cache',
...this.authHeaders,
...headers,
},
};

const withBody = [this.Method.PUT, this.Method.PATCH, this.Method.POST];

if (withBody.indexOf(method) !== -1) {
if (body) {
parameters.body = JSON.stringify(body);
if (method === this.Method.PUT) {
parameters.headers['Content-Length'] = 0;
}
}

return fetch(finalUrl, parameters);
};

/* eslint-disable no-unused-vars */
get = ({ fetchParameters, ...config }: CallParameters): CallType => ({
type: 'get',
params: {},
...config,
fetchParameters: merge(
{ method: this.Method.GET, headers: { Accept: this.Accept.JSON } },
fetchParameters
),
});

list = ({ fetchParameters, ...config }: CallParameters): CallType => ({
type: 'list',
params: {},
...config,
fetchParameters: merge(
{ method: this.Method.GET, headers: { Accept: this.Accept.JSON } },
fetchParameters
),
});

/**
* Sets the authorization headers given an access token.
*
* @abstract
* @param {string} token The oAuth access token
*/
setAuthHeaders = token => {
setAuthHeaders = (token: string) => {
this.authHeaders = { Authorization: `token ${token}` };
};

Expand All @@ -82,7 +134,7 @@ export class Client {
* @async
* @param {Response} response
*/
getCount = async response => {
getCount = async (response: Response) => {
if (!response.ok) {
return 0;
}
Expand All @@ -104,7 +156,7 @@ export class Client {
});
};

getNextPageUrl = response => {
getNextPageUrl = (response: Response) => {
const { headers } = response;
const link = headers.get('link');
const nextLink = link
Expand All @@ -130,55 +182,60 @@ export class Client {
*
* @param {string} userId
*/
getEventsReceived: async (userId, params) => {
return this.call(`users/${userId}/received_events`, params).then(
response => ({
response,
nextPageUrl: this.getNextPageUrl(response),
schema: Schemas.EVENT_ARRAY,
})
);
},
getStarredReposForUser: async (userId, params) => {
return this.call(`users/${userId}/starred`, params).then(response => ({
response,
nextPageUrl: this.getNextPageUrl(response),
getEventsReceived: (
userId: string,
params: SpecialParameters = {}
): CallParameters =>
this.list({
endpoint: `users/${userId}/received_events`,
params: params || {},
schema: Schemas.EVENT_ARRAY,
paginationArgs: [userId],
}),

getStarredReposForUser: (userId: string, params: SpecialParameters = {}) =>
this.list({
endpoint: `users/${userId}/starred`,
params,
schema: Schemas.REPO_ARRAY,
}));
},
paginationArgs: [userId],
}),
};
search = {
repos: async (q, params) => {
return this.call(`search/repositories?q=${q}`, params).then(response => ({
response,
nextPageUrl: this.getNextPageUrl(response),
repos: (q: string, params: SpecialParameters = {}) =>
this.list({
endpoint: `search/repositories?q=${q}`,
params,
schema: Schemas.REPO_ARRAY,
paginationArgs: [q],
normalizrKey: 'items',
}));
},
users: async (q, params) => {
return this.call(`search/users?q=${q}`, params).then(response => ({
response,
nextPageUrl: this.getNextPageUrl(response),
}),

users: (q: string, params: SpecialParameters = {}) =>
this.list({
endpoint: `search/users?q=${q}`,
params,
schema: Schemas.USER_ARRAY,
paginationArgs: [q],
normalizrKey: 'items',
}));
},
}),
};
orgs = {
getById: async (orgId, params) => {
return this.call(`orgs/${orgId}`, params).then(response => ({
response,
/**
* Get org by id
*/
getById: (orgId: string, params: SpecialParameters = {}) =>
this.get({
endpoint: `orgs/${orgId}`,
params,
schema: Schemas.ORG,
}));
},
getMembers: async (orgId, params) => {
return this.call(`orgs/${orgId}/members`, params).then(response => ({
response,
nextPageUrl: this.getNextPageUrl(response),
}),
getMembers: (orgId: string, params: SpecialParameters = {}) =>
this.list({
endpoint: `orgs/${orgId}/members`,
params,
schema: Schemas.USER_ARRAY,

}));
},
paginationArgs: [orgId],
}),
};
}
Loading