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"
}
}
45 changes: 41 additions & 4 deletions controllers/pokemon.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,53 @@
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');
try {
const allFaves = await db.pokemon.findAll()
console.log(allFaves)
res.render('faves.ejs', { allFaves })
} catch (err) {
console.log(err)
res.status(500).send("Server had a 500 error")
}

});

// 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);
const pokeName = req.body.name
try {
await db.pokemon.findOrCreate({
where: {
name: pokeName
}
})
res.redirect('/pokemon')

} catch(err) {
console.log(err)
res.send(500).send("Server had an error")
}
});

// GET /pokemon/:name -- renders a show page with info about the pokemon
router.get('/:name', async (req, res) => {
const url = `http://pokeapi.co/api/v2/pokemon/${req.params.name}`
axios.get(url)
.then(response => {
res.render('detail.ejs', {
pokemon: response.data
})
})
.catch(err => {
console.log(err)
res.status(500).send("Server ist kaput")
})
})

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()
28 changes: 28 additions & 0 deletions migrations/20230404014856-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.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;
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.STRING
}, {
sequelize,
modelName: 'pokemon',
});
return pokemon;
};
Loading