-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
83 lines (69 loc) · 1.93 KB
/
index.js
File metadata and controls
83 lines (69 loc) · 1.93 KB
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
//import canonize from './canonize'
// check the "import" is work in Node v7
// повторить работу модулей
var express = require('express');
var fetch = require('isomorphic-fetch')
var Promise = require('bluebird');
const _ = require('lodash');
const can = require('./canonize');
var app = express();
const __DEV__ = true;
app.get('/canonize', (req, res)=>{
return ( res.json({
url: req.query.url,
username: can.canonize(req.query.url),
}));
});
async function getPokemons(url, i = 0) {
//console.log('getPokemons', url);
const response = await fetch(url);
const page = await response.json();
const pokemons = page.results;
if (__DEV__ && i >= 2) {
return pokemons;
}
if(page.next){
const pokemons2 = getPokemons(page.next, i + 1);
return [
...pokemons,
...pokemons2
]
}
return pokemons;
}
async function getPokemon(url) {
const response = await fetch(url);
const pokemon = await response.json();
return pokemon;
}
const baseUrl = 'https://pokeapi.co/api/v2';
const fields = ['id', 'name', 'weight', 'height'];
const pokemonsUrl = `${baseUrl}/pokemon`;
getPokemons(pokemonsUrl).then(pokemons => {
console.log(pokemons.length);
});
app.get('/', async (req, res) => {
try {
const pokemonsUrl = `${baseUrl}/pokemon`;
const pokemonsInfo = await getPokemons(pokemonsUrl);
const pokemonsPromises = pokemonsInfo.slice(0, 2).map(info => {
return getPokemon(info.url);
});
const pokemonsFull = await Promise.all(pokemonsPromises);
const pokemons = pokemonsFull.map( (pokemon) => {
return _.pick(pokemon, fields);
});
console.log(pokemons);
return (res.json({
pokemons
}));
} catch(err){
console.log(err);
return res.json({err});
};
});
app.listen(3000, ()=>{
console.log('Hi there!');
});
// If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
// Full webpack example : https://github.com/stujo/javascript-async-await