forked from sugardave/pokedex-promise-v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
175 lines (158 loc) · 5.7 KB
/
index.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
const rp = require('request-promise');
const cache = require('memory-cache');
const async = require('async');
const CACHE_LIMIT = 1000000 * 1000; // 11 days
const versionUrl = '/api/v2/';
getJSON = function (opts) {
// retrive possible content from volatile memory
const url = opts.url;
const cb = opts.callback;
const withCredentials = opts.withCredentials;
const cachedResult = cache.get(url);
if (cachedResult !== null) {
return new Promise(function(resolve, reject) {
if (cb) {
// call callback without errors
cb(cachedResult, false);
}
resolve(cachedResult);
});
} else {
// retrive data from the web
const options = {
url: url,
json: true,
withCredentials: withCredentials
};
return rp.get(options)
.catch(function (error) {
if (!cb) {
// throw if a Promise
throw error;
} else {
// call the callback with error as second parameter
cb('error', error);
}
})
.then(function (response) {
if (response) {
// if there was an error
if (response.statusCode !== undefined && response.statusCode !== 200) {
if (!cb) {
// throw if a Promise
throw response;
} else {
// call the callback with error as second parameter
cb('error', response);
}
} else {
// if everithing was good
// cache the object in volatile memory
cache.put(url, response, CACHE_LIMIT);
// if a callback is present
if (cb) {
// call it, without errors
cb(response, false);
} else {
// return the Promise
return response;
}
}
}
});
}
};
const endpoints = [
['getBerryByName', 'berry'],
['getBerryFirmnessByName', 'berry-firmness'],
['getBerryFlavorByName', 'berry-flavor'],
['getContestTypeByName', 'contest-type'],
['getContestEffectById', 'contest-effect'],
['getSuperContestEffectById', 'super-contest-effect'],
['getEncounterMethodByName', 'encounter-method'],
['getEncounterConditionByName', 'encounter-condition'],
['getEncounterConditionValueByName', 'encounter-condition-value'],
['getEvolutionChainById', 'evolution-chain'],
['getEvolutionTriggerByName', 'evolution-trigger'],
['getGenerationByName', 'generation'],
['getPokedexByName', 'pokedex'],
['getVersionByName', 'version'],
['getVersionGroupByName', 'version-group'],
['getItemByName', 'item'],
['getItemAttributeByName', 'item-attribute'],
['getItemCategoryByName', 'item-category'],
['getItemFlingEffectByName', 'item-fling-effect'],
['getItemPocketByName', 'item-pocket'],
['getMoveByName', 'move'],
['getMoveAilmentByName', 'move-ailment'],
['getMoveBattleStyleByName', 'move-battle-style'],
['getMoveCategoryByName', 'move-category'],
['getMoveDamageClassByName', 'move-damage-class'],
['getMoveLearnMethodByName', 'move-learn-method'],
['getMoveTargetByName', 'move-target'],
['getLocationByName', 'location'],
['getLocationAreaByName', 'location-area'],
['getPalParkAreaByName', 'pal-park-area'],
['getRegionByName', 'region'],
['getAbilityByName', 'ability'],
['getCharacteristicById', 'characteristic'],
['getEggGroupByName', 'egg-group'],
['getGenderByName', 'gender'],
['getGrowthRateByName', 'growth-rate'],
['getNatureByName', 'nature'],
['getPokeathlonStatByName', 'pokeathlon-stat'],
['getPokemonByName', 'pokemon'],
['getPokemonColorByName', 'pokemon-color'],
['getPokemonFormByName', 'pokemon-form'],
['getPokemonHabitatByName', 'pokemon-habitat'],
['getPokemonShapeByName', 'pokemon-shape'],
['getPokemonSpeciesByName', 'pokemon-species'],
['getStatByName', 'stat'],
['getTypeByName', 'type'],
['getLanguageByName', 'language']
];
const Pokedex = (function() {
function Pokedex(opts, pokeUrl){
this.opts = opts || {};
this.pokeUrl = pokeUrl || 'http://pokeapi.co';
}
// add to Pokedex.prototype all our endpoint functions
endpoints.forEach(function (endpoint) {
Pokedex.prototype[endpoint[0]] = function (input, cb, params) {
var param = params || '';
if (input) {
// if the user has submitted a Name or an Id, return the Json promise
if (typeof input === 'number' || typeof input === 'string') {
return this.request(this.pokeUrl + versionUrl + endpoint[1] + '/' + input + '/' + param, cb);
}
// if the user has submitted an Array
// return a new promise which will resolve when all getJSON calls are ended
else if (typeof input === 'object') {
var toReturn = []
return new Promise(function (resolve, reject){
// fetch data asynchronously to be faster
async.forEachOf(input, function (name){
//get current input data and then try to resolve
this.request(this.pokeUrl + versionUrl + endpoint[1] + '/' + name + '/' + param, function (response){
toReturn.push(response);
if(toReturn.length === input.length){
if (cb) {
cb(toReturn);
}
resolve(toReturn);
}
});
})
});
}
} else {
return this.request(this.pokeUrl + versionUrl + endpoint[1] + param, cb);
}
}
});
Pokedex.prototype.request = function (url, cb) {
return getJSON({withCredentials: this.opts.hasOwnProperty('withCredentials') ? this.opts.withCredentials : true, url: url, callback: cb});
}
return Pokedex;
})();
module.exports = Pokedex;