-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathapiHelper.js
93 lines (81 loc) · 2.35 KB
/
apiHelper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Copyright (c) 2015-present, Facebook Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*
* @flow strict
*/
import DataLoader from 'dataloader';
import { getFromLocalUrl } from '../api';
const localUrlLoader = new DataLoader(urls =>
Promise.all(urls.map(getFromLocalUrl)),
);
/**
* Objects returned from SWAPI don't have an ID field, so add one.
*/
function objectWithId(obj: Object): Object {
obj.id = parseInt(obj.url.split('/')[5], 10);
return obj;
}
/**
* Given an object URL, fetch it, append the ID to it, and return it.
*/
export async function getObjectFromUrl(url: string): Promise<Object> {
const data = await localUrlLoader.load(url);
return objectWithId(data);
}
/**
* Given an object URL, return the Swapi type from it
* @param url
*/
export function getSwapiTypeFromUrl(url: string): string {
return url.split('/')[4];
}
/**
* Given a type and ID, get the object with the ID.
*/
export async function getObjectFromTypeAndId(
type: string,
id: string,
): Promise<Object> {
return await getObjectFromUrl(`https://swapi.co/api/${type}/${id}/`);
}
type ObjectsByType = {
objects: Array<Object>,
totalCount: number,
};
/**
* Given a type, fetch all of the pages, and join the objects together
*/
export async function getObjectsByType(type: string): Promise<ObjectsByType> {
let objects = [];
let nextUrl = `https://swapi.co/api/${type}/`;
while (nextUrl) {
// eslint-disable-next-line no-await-in-loop
const pageData = await localUrlLoader.load(nextUrl);
objects = objects.concat(pageData.results.map(objectWithId));
nextUrl = pageData.next;
}
objects = sortObjectsById(objects);
return { objects, totalCount: objects.length };
}
export async function getObjectsFromUrls(urls: string[]): Promise<Object[]> {
const array = await Promise.all(urls.map(getObjectFromUrl));
return sortObjectsById(array);
}
function sortObjectsById(array: { id: number }[]): Object[] {
return array.sort((a, b) => a.id - b.id);
}
/**
* Given a string, convert it to a number
*/
export function convertToNumber(value: string): ?number {
if (['unknown', 'n/a'].indexOf(value) !== -1) {
return null;
}
// remove digit grouping
const numberString = value.replace(/,/, '');
return Number(numberString);
}