Skip to content

Instantly share code, notes, and snippets.

@Dmitriy-8-Kireev
Last active January 13, 2019 16:28
Show Gist options
  • Save Dmitriy-8-Kireev/212d5286942da7e3a7bb1a9c5747a560 to your computer and use it in GitHub Desktop.
Save Dmitriy-8-Kireev/212d5286942da7e3a7bb1a9c5747a560 to your computer and use it in GitHub Desktop.
1)Варианты присваивания id ключам + map 2) Api для проекта с трансформациями
// Первый вариант
{list.map(function (item) {
return (
# leanpub-start-insert
<div key={item.objectID}>
# leanpub-end-insert
<span>
<a href={item.url}>{item.title}</a>
</span>
<span>{item.author}</span>
<span>{item.num_comments}</span>
<span>{item.points}</span>
</div>
);
})}
// Второй вариант
# leanpub-start-insert
{list.map(item =>
# leanpub-end-insert
<div key={item.objectID}>
<span>
<a href={item.url}>{item.title}</a>
</span>
<span>{item.author}</span>
<span>{item.num_comments}</span>
<span>{item.points}</span>
</div>
# leanpub-start-insert
)}
# leanpub-end-insert
// ---------------------------------------------//
Api для проекта с трансформациями
export default class SwapiService {
_apiBase = "https://swapi.co/api";
async getResource(url) {
const res = await fetch(`${this._apiBase}${url}`);
if (!res.ok) {
throw new Error(`Could not fetch ${url}` + `, received ${res.status}`);
}
return await res.json();
}
async getAllPeople() {
const res = await this.getResource(`/people/`);
return res.results.map(this._transformPerson);
}
async getPerson(id) {
const person = await this.getResource(`/people/${id}/`);
return this._transformPerson(person);
}
async getAllPlanets() {
const res = await this.getResource(`/planets/`);
return res.results.map(this._transformPlanet);
}
async getPlanet(id) {
const planet = await this.getResource(`/planets/${id}/`);
return this._transformPlanet(planet);
}
async getAllStarships() {
const res = await this.getResource(`/starships/`);
return res.results.map(this._transformStarship);
}
async getStarship(id) {
const starship = this.getResource(`/starships/${id}/`);
return this._transformStarship(starship);
}
_extractId(item) {
const idRegExp = /\/([0-9]*)\/$/;
return item.url.match(idRegExp)[1];
}
_transformPlanet(planet) {
return {
id: this._extractId(planet),
name: planet.name,
population: planet.population,
rotationPeriod: planet.rotation_period,
diameter: planet.diameter
};
}
_transformStarship(starship) {
return {
id: this._extractId(starship),
name: starship.name,
model: starship.model,
manufacturer: starship.manufacturer,
costInCredits: starship.costInCredits,
length: starship.length,
crew: starship.crew,
passengers: starship.passengers,
cargoCapacity: starship.cargoCapacity
};
}
_transformPerson(person) {
return {
id: this._extractId(person),
name: person.name,
gender: person.gender,
birthYear: person.birthYear,
eyeColor: person.eyeColor
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment