This will expand on the Cruddy Board Games project. You can copy your solution into this new repository, or you can copy this completed solution and begin from there.
We will be replacing the games.json
"database" with an actual database. We will use PostgreSQL and Sequelize.
Verb | Path | Action | Used for |
---|---|---|---|
GET | /games | index | display a list of all games |
GET | /games/new | new | return an HTML form for creating a new game |
POST | /games | create | create a new game (using form data from /games/new) |
GET | /games/:name | show | display a specific game |
GET | /games/:name/edit | edit | return an HTML form for editing a game |
PUT | /games/:name | update | update a specific game (using form data from /games/:name/edit) |
DELETE | /games/:name | destroy | deletes a specific game |
-
Install the modules we need.
npm install --save pg pg-hstore sequelize
-
Create the database.
createdb cruddy_board_games_db
-
Initialize.
sequelize init
- Configure your
config.json
file.
- Use the
sequelize
command line tool to create agame
table in our database.
sequelize model:create --name game --attributes ...
- What columns should be on
game
?
- Run the migrations.
sequelize db:migrate
- On the top of
app.js
file, require the models
var db = require("./models");
- Delete
games.json
,getGames()
, andsaveGames()
. Replace calls to those functions with appropriate usages ofdb.game
.
Example, for the game indexing route:
app.get('/games', function(req, res) {
var games = getGames();
res.render('games-index', { games: games });
});
turns into
app.get('/games', function(req, res) {
db.game.findAll().then(function(games) {
res.render('games-index', { games: games });
}).catch(function(error) {
res.status(404).send(error);
});
});
Add numberOfPlayers
to the game
model.
sequelize migration:create --name add-number-of-players-to-game
Refer to Sequelize migration documentation.
Edit the new migration file migrations/xxxxxxxxxxx-add-number-of-players-to-game.js
.
- In the
up
function, useaddColumn
- In the
down
function, useremoveColumn
- Migrate!
sequelize db:migrate
- Update the model file
models/game.js
. Add the property:numberOfPlayers: DataTypes.INTEGER
Make sure you also update the show, new game, and edit game pages to use the new numberOfPlayers
property.
Add some validations to our data. For example: num players should be at least 1. Game name should be at least X characters long, etc ...
Refer to the git note book and sequelize's documentation.
All content is licensed under a CCBYNCSA 4.0 license. All software code is licensed under GNU GPLv3. For commercial use or alternative licensing, please contact [email protected].