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
7 changes: 7 additions & 0 deletions config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"development": {
"database": "pokedex",
"host": "127.0.0.1",
"dialect": "postgres"
}
}
44 changes: 39 additions & 5 deletions controllers/pokemon.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,50 @@
const express = require('express');
const router = express.Router();
const db = require("../models");
const axios = require('axios');

// GET /pokemon - return a page with favorited Pokemon
router.get('/', (req, res) => {
router.get('/', async (req, res) => {
// TODO: Get all records from the DB and render to view
res.send('Render a page of favorites here');
});
const allFaves = await db.pokemon.findAll();
try {
res.render("pokemon/index.ejs", {
pokemon:allFaves
})
} catch(err) {
console.log(err);
res.status(500).send("Server had an error.")
// res.send('Render a page of favorites here');
}});

// POST /pokemon - receive the name of a pokemon and add it to the database
router.post('/', (req, res) => {
router.post('/', async (req, res) => {
// TODO: Get form data and add a new record to DB
res.send(req.body);
// console.log(req.body);
try {
const newPokemon = await db.pokemon.create({name: req.body.name, url: req.body.url })
res.redirect('/pokemon')
} catch (err) {
console.log(err);
res.status(500).send("Server had an error.")
}

// res.send(req.body);
});

//GET /pokemon/pokemon_name
router.get("/:name", (req, res) => {
pokeName = req.params.name;
console.log(pokeName)
let pokemonUrl = `https://pokeapi.co/api/v2/pokemon/${pokeName}`;
axios.get(pokemonUrl).then(apiResponse => {
let pokemon = apiResponse.data
console.log(pokemon.stats.stat)
res.render("pokemon/show", {
pokemon: pokemon,
// officialArt: pokemon.sprites.other["official-artwork"].front_default
})
})
})

module.exports = router;
37 changes: 37 additions & 0 deletions db-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Make sure to require your models in the files where they will be used.
const db = require('./models');

db.pokemon.create({
name: 'pikachu'
})
.then(poke => {
console.log('Created: ', poke.name)
db.pokemon.findOne({
where: {
name: 'pikachu'
}
})
.then(poke => {
console.log('Found: ', poke.name)
})
.catch(console.log)
})
.catch(console.log)

// create some pokemon with async/await syntax
async function createPokemon() {
try {
const newPokemon = await db.pokemon.create({ name: 'charizard' })
console.log('the new pokemon is:', newPokemon)
const foundPokemon = await db.pokemon.findOne({
where: {
name: 'charizard'
}
})
console.log('the found pokemon is:', foundPokemon)
} catch (err) {
console.log(err)
}
}

createPokemon()
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ app.get('/', (req, res) => {
let pokemonUrl = 'http://pokeapi.co/api/v2/pokemon/?offset=0&limit=151';
// Use request to call the API
axios.get(pokemonUrl).then(apiResponse => {
// console.log(apiResponse.data)
let pokemon = apiResponse.data.results;
res.render('index', { pokemon: pokemon });
res.render('index',
{ pokemon: pokemon });
})
});

Expand Down
31 changes: 31 additions & 0 deletions migrations/20230404025806-create-pokemon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('pokemons', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
url: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('pokemons');
}
};
31 changes: 31 additions & 0 deletions migrations/20230404043934-create-pokemon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('pokemons', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
url: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('pokemons');
}
};
43 changes: 43 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(file => {
return (
file.indexOf('.') !== 0 &&
file !== basename &&
file.slice(-3) === '.js' &&
file.indexOf('.test.js') === -1
);
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
24 changes: 24 additions & 0 deletions models/pokemon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class pokemon extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
pokemon.init({
name: DataTypes.STRING,
url: DataTypes.STRING
}, {
sequelize,
modelName: 'pokemon',
});
return pokemon;
};
Loading