Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

kenan - pokedex-exp-post #230

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
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
127 changes: 91 additions & 36 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,125 @@
const express = require('express');
const jsonfile = require('jsonfile');

const bodyParser = require('body-parser');
const path = require('path');
const port = 3000;
const FILE = 'pokedex.json';

/**
* ===================================
* Configurations and set up
* ===================================
*/

// Init express app
const reactViews = require('express-react-views');
const app = express();

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.set('views', __dirname + '/views');
app.engine('jsx', reactViews.createEngine());
app.set('view engine', 'jsx');
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => console.log(`~~~ Tuning in to the waves of port ${port} ~~~`));

/**
* ===================================
* Routes
* ===================================
*/

app.get('/pokemon/:id', (request, response) => {
app.get('/pokemon/new', (req, res) => {
res.render('form');
});
app.use('/pokemon', preventDuplicate);
app.post('/pokemon', addPokemon);
app.get('/pokemon/:id', viewPokemonById);
app.get('/', (request, response) => {
response.send("yay");
});

// utils
const getJson = async () => await jsonfile.readFile(FILE);
const writeJson = async (data) => await jsonfile.writeFile(FILE, data);

// get json from specified file
// controllers
function preventDuplicate(req, res, next ) {
getJson()
.then(data => checkDuplicates(data, req))
.then( hasDup =>handleIfDuplicates (hasDup,next,res));
}

function checkDuplicates(data, req) {
return data.pokemon.some(item =>
item.name === req.body.name ||
item.id === req.body.id ||
item.num === req.body.num)
}

function handleIfDuplicates(hasDuplicate,next,res) {
if(hasDuplicate) {
res.render("There is already an pokemon with id, name , or number");
} else {
next();
}
}

function getInvalidInputFields(id, num, name, img, height, weight ) {
const errors = {};
const params = {id, num, name, img, height, weight};
for (const key in params) {
if (!params[key]) {
errors[key] = `${key} is missing`
}
}
return errors
}

function addPokemon(req, res) {
const {id, num, name, img, height, weight} = req.body;
const errors = getInvalidInputFields(id, num, name,img, height, weight);
console.log("error are");
console.log(errors);
if (Object.keys(errors).length) {
console.log("this is run");
console.log({errors});
return res.render('form', {errors});
}
else {
getJson()
.then(data =>_addPokemon(data, id, num, name, img, height, weight))
.then(writeJson)
}

}

function _addPokemon(data, id, num, name, img, height, weight) {
data.pokemon.push({id, num, name, img, height, weight});
return data;
}


function viewPokemonById(response, request) {
jsonfile.readFile(FILE, (err, obj) => {

// check to make sure the file was properly read
if( err ){

console.log("error with json read file:",err);
if (err) {
console.log("error with json read file:", err);
response.status(503).send("error reading filee");
return;
return;
}
// obj is the object from the pokedex json file
// extract input data from request
let inputId = parseInt( request.params.id );

let inputId = parseInt(request.params.id);
var pokemon;

// find pokemon by id from the pokedex json file
for( let i=0; i<obj.pokemon.length; i++ ){
for (let i = 0; i < obj.pokemon.length; i++) {

let currentPokemon = obj.pokemon[i];

if( currentPokemon.id === inputId ){
if (currentPokemon.id === inputId) {
pokemon = currentPokemon;
}
}

if (pokemon === undefined) {

// send 404 back
response.status(404);
response.send("not found");
} else {

response.send(pokemon);
}
});
});

app.get('/', (request, response) => {
response.send("yay");
});

/**
* ===================================
* Listen to requests on port 3000
* ===================================
*/
app.listen(3000, () => console.log('~~~ Tuning in to the waves of port 3000 ~~~'));
}
Loading