Skip to content
Open
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
50 changes: 50 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Remeber we passed data to EJS, we're using it here.
// It gives us a string of names seperated with ','. Ex. pikachu,ivysaur,charmeleon
// We're using split method to split on every ',' and make it an element of the array.
let pokemonsArray = "<%= pokemons %>".split(",");
// we are setting all pokemon to an empty array
let allPokemons = [];
// window.onload will be fired when the entire page loads
window.onload = async () => {
// we are targeting the get-pokemon id and adding an event listener
let btn = document
.getElementById("get-pokemon")
.addEventListener("click", () => {
const pokemonDiv = document.getElementById("pokemonDiv");
// .forEach() we typically need an item and an index, but its does not matter how many arguments are passed.
allPokemons.forEach((pokemon) => {
pokemonDiv.innerHTML += `<div class="pokemon-card ${pokemon.types[0].type.name}" >
<a href="/${pokemon.id}">
<div class="header">
<p>${pokemon.name}</p>
<p>#${pokemon.id}</p>
</div>
<div>
<img
src="${pokemon.img}"
alt="${pokemon.name}"
/>
</div>
</a>
</div>`;
});
});

// We're making another API request below since the server gives us names of the pokemons.
// We're using these names to make a request to API and then get data for specific Pokemon.
pokemonsArray.forEach(async (pokemon) => {
let pokemonInfo = {};

await fetch("https://pokeapi.co/api/v2/pokemon/" + pokemon)
.then((res) => res.json())
.then((newRes) => {
// then extracting the required data & pushing it to an array.
allPokemons.push({
id: newRes.id,
name: newRes.name,
img: newRes.sprites.other["official-artwork"]["front_default"], //object keys that have spaces or dashes can be accessed using ['key-name']
types: newRes.types,
});
});
});
};
34 changes: 34 additions & 0 deletions dbInsert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const fetch = require('node-fetch');
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For organization, i would recommend putting this in the rest folder


const Sequelize = require('sequelize');

// creating a new connection. Passing db name, user, and password
const conn = new Sequelize('pokedex', 'root', 'password', {
host: 'localhost',
dialect: 'mysql'
});

// create a function that insert pokemon into the database. Passing 3 values name, id, and sprites
function insertIntoDb({name,id,sprite}){
conn.query(`Insert into POKEMON (pokename, id, sprites) VALUES ("${name}",${id},"${sprite}");`); // this is my query, quotes for text type, none for number
}
function getRange(start,end){ // creating an empty array, looping thru the range of pokemon I want to collect
const arr = [];
for(let i =start; i <= end; i++){
arr.push(i); // pushing each pokemon into the array
}
return arr; // returning the array after pokemon are collected
}
function getAllPokemon(){
// the endpoint is our point of entry, this function will render our range of pokemon.
const endpoint = `https://pokeapi.co/api/v2/pokemon/`
return Promise.all(getRange(1,10).map(id => fetch(`${endpoint}${id}`) // we are returning all "promises" which is our pokemon range specified in the parameters.
// we are mapping each pokemon to its id that we are fetching from the endpoint.
.then(res => res.json()) // we are using json on our response
.then(({name,id,sprites:{front_default:sprite}}) => ({name,id,sprite})))); //
}
// lastly we are invoking getAllPokemon then for each pokemon, we are inserting it into our database.
getAllPokemon().then(pokemon => {
pokemon.forEach(insertIntoDb)
});
// sequelize.query('show tables').then(console.log)
131 changes: 122 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,124 @@
const express = require('express')
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For organization, i would recommend putting this in the rest folder

const app = express()
const port = 3000
// "express" and "app" are essential in any node/express app.
// require('library-name')
const express = require("express");
const app = express(); //initializes express app

app.get('/', (req, res) => {
res.send('Hello World!')
})
// To connect to the database, you must create a Sequelize instance.
// This can be done by either passing the connection parameters separately to the Sequelize constructor or by passing a single connection URI
const Sequelize = require('sequelize');

app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
// const sequelize = new Sequelize('mysql://user:Azeez:3306/pokedex', {
// host: 'localhost',
// dialect: 'mysql'
// });

// (async () => {
// try {
// await sequelize.authenticate();
// console.log('Connection to the database successful!');
// } catch (error) {
// console.error('Error connecting to the database: ', error);
// }
// })
// ();


const sequelize = new Sequelize('pokedex', 'root', 'password', {
host: 'localhost',
dialect: 'mysql'
});

sequelize.query('show tables').then(console.log)

// axios is for making api/ajax requests.
const axios = require("axios");
// ejs is our view engine. We're using EJS because we have to pass data to our frontend templates
const ejs = require("ejs");

// Setting EJS as our view engine
app.set("view engine", "ejs");

// This middleware is used to tell app that our data will be in JSON format.
app.use(express.json());

app.use(express.static('public'))
app.use('/css', express.static(__dirname + 'public/css'))
// app.get('', (req, res) => {
// res.send(__dirname + '/views/allPokemon.html')

// });

// This will be our root route
app.get("/", (req, res) => {
// the response is converted to json and our two routes are defined in an array. All Pokemon are in the 1st route and pokemon by id is the second route
res.json({
routes: [
{
name: "All Pokemons",
url: "/pokemons",
},
{
name: "Pokemon with ID",
url: "/pokemon/id-here",
},
],
});
});
// this is our pokemon route. We have use async for await to work.
app.get("/pokemons", async (req, res) => {
let apiData;
// creating an empty array for pokemon
let pokemonArray = [];

// axios is a library for requesting APIs, just like fetch or XML but it makes things even
// easier than fetch()

await axios
.get("https://pokeapi.co/api/v2/pokemon") // we are getting the data from this api and setting it to the var apidData.
.then((data) => (apiData = data.data));

// pushing name of each pokemon to the array
apiData.results.forEach((pokemon) => {
pokemonArray.push(pokemon.name);
});

// this will render pokemons.ejs (located in views/pokemons.ejs) with pokemonArray.
// we can use this data with pokemon variable in our EJS template.
res.render("pokemons", { pokemons: pokemonArray });
});

// :id creates a dynamic url, we define the id in the parameters in below function.
app.get("/:id", async (req, res) => {
let apiData;

// Getting the ID from the url
const id = req.params.id;

let pokemon = {
id: "",
name: "",
img: "",
types: [],
};

try {
await axios
.get("https://pokeapi.co/api/v2/pokemon/" + id) // initial response will only be 20 pokemon. The ID can be enter to see additional pokemon
.then((data) => (apiData = data.data));
//connecting the pokemon id, name, img, and type with its data for id, name, image, and type.
pokemon.id = apiData.id;
pokemon.name = apiData.name;
pokemon.img = apiData.sprites.other["official-artwork"]["front_default"];
pokemon.types = apiData.types;

res.render("pokemon", { pokemon: pokemon });
} catch (e) {
res.send(e);
}
});

// The server will run on the port which we'll pass here.
// The server can be started with 'npm start' in the terminal
app.listen(8000, () => {
console.log(`Listening to 8000`);
});
Loading