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"
}
}
47 changes: 38 additions & 9 deletions controllers/pokemon.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,45 @@
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) => {
// TODO: Get all records from the DB and render to view
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) => {
// TODO: Get form data and add a new record to DB
res.send(req.body);
router.post("/", async (req, res) => {
try {
await db.pokemon.findOrCreate({
where: req.body
})
res.redirect('pokemon')
} catch(err){
console.log(err)
res.status(500).send("Server had an error")
}
})

router.get('/', async (req, res) => {
try {
const allPokemon = await db.pokemon.findAll()
res.render('pokemon', {allPokemon})
} catch(err) {
console.log(err)
res.status(500).send('Server had an error')
}
})

router.get('/:name', (req, res) => {
let pokemonName = req.params.name;
let pokemonDetailsUrl = `https://pokeapi.co/api/v2/pokemon/${pokemonName}`;

// Use axios to call the API
axios.get(pokemonDetailsUrl)
.then(apiResponse => {
let pokemon = apiResponse.data;
res.render('show', { pokemon: pokemon });
})
.catch(error => {
console.log(error);
res.status(500).send(error.message);
});
});

module.exports = router;
36 changes: 36 additions & 0 deletions db-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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()
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const express = require('express');
const axios = require('axios');
const ejsLayouts = require('express-ejs-layouts');
const db = require('./models')

const app = express();
const port = process.env.PORT || 3000;
Expand All @@ -20,6 +21,7 @@ app.get('/', (req, res) => {
})
});


// Imports all routes from the pokemon routes file
app.use('/pokemon', require('./controllers/pokemon'));

Expand Down
28 changes: 28 additions & 0 deletions migrations/20230404022322-create-pokemon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'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.TEXT
},
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;
23 changes: 23 additions & 0 deletions models/pokemon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'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.TEXT
}, {
sequelize,
modelName: 'pokemon',
});
return pokemon;
};
Loading