CommandShift
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- tags: sequelize,practical --- # Sequelize Introduction Practical: Have I Fed the Cat? For this practical session, you will be building a simple web app to track when the cat was last fed. ## User Stories ``` As a cat owner So I can organise my cat's feeding I want to be able to create a cat with description in the database ``` ``` As a cat owner So I can keep track of feedings I want to be able to record the last time I fed the cat ``` ``` As a cat onwer So I can check when the cat was last fed I want to be able to read the last time I fed the cat ``` ## Requirements From the user stories, we can infer some requirements on what sort of information our app should store. The main thing we want to keep track of is when a cat was last fed, but to prevent confusion, we should also have a few ways to differentiate between cats. This is one way our `Cat` table could look: ``` { name: STRING, breed: STRING, markings: STRING, lastFed: DATE } ``` We can also see from the user stories that we are going to want to be able to `CREATE`, `READ` and `UPDATE` cats. `DELETE` might also be useful, but isn't nessesary for this practical. From this, we can expect to make the following `endpoints` in our web app: ### POST /cats This endpoint creates a new cat record in the database ```javascript Request Body: { "name": STRING, "breed": STRING, "markings": STRING } Response Status: 201 Response Body: { "id": INTEGER "name": STRING, "breed": STRING, "markings": STRING "lastFed": NULL } ``` Note that we don't need to supply the `lastFed` property when creating the cat record, this is because can be handled automatically, and at the point of creating the record should be `null` (never fed). ### GET /cats This endpoint will return a list of all cats in the database. Example response: ```javascript Response Status: 200 Response Body: [ { "id": INTEGER "name": STRING, "breed": STRING, "markings": STRING "lastFed": DATE }, { "id": INTEGER "name": STRING, "breed": STRING, "markings": STRING "lastFed": DATE }, ] ``` ### GET /cats/:catId This endpoint returns a single cat record, where `:catId` is the `id` of the cat in the database ```javascript Response Status: 200 Response Body: { "id": INTEGER "name": STRING, "breed": STRING, "markings": STRING "lastFed": DATE } ``` ### PATCH /cats/:catId Using this endpoint, users can update a single cat record in the database, where `:catId` is the `id` of the cat in the database. ```javascript Request Body: { lastFed: DATE } Response Status: 200 ``` ### Optional: PATCH /feed/cat/:catId We could make our interface simpler for requests that we expect to be perfoming regularly. In this case we could have our client send a simple `PATCH` request without a body, and have the app automatically update the time the cat was fed. ``` Response Status: 200 ``` ## Getting Set Up In order to start using Sequelize, we will need to set up a simple express app, and a Postgres database (If you already have a docker container running for another project then you can just use that). 1. Set up a new git repository: ```bash mkdir have-i-fed-the-cat-app cd have-i-fed-the-cat-app git init npm init -y ``` 1. Use PGAdmin to create a database for the app to store data in: ```sql CREATE DATABASE have_i_fed_the_cat_app; ``` 1. Install `express`, `sequelize` and `pg` as dependancies: ```bash npm i -S express sequelize pg ``` 1. Install `nodemon` as a dev-dependancy: ```bash npm i -D nodemon ``` 1. Create a `.gitignore` and add your `node_modules` to it: ```bash echo /node_modules >> .gitignore ``` Or use the `gitignore` node module to autogenerate one for you: ```bash npx gitignore node ``` 1. In your `package.json`, add a `start` script with the following command: ```json ... "scripts": { "start": "nodemon index.js" }, ... ``` We won't worry about `dotenv` for the scope of this exercise. 1. Create an `index.js` and a `src` directory containing an `app.js`. Your project structure should look like this (excluding `node_modules`): ``` have-i-fed-the-cat-app ├── index.js ├── package-lock.json ├── package.json └── src └── app.js 1 directory, 4 files ``` 1. Set up a simple express app in your `src/app.js`: ```javascript // In src/app.js add this code: const express = require('express'); const app = express(); // we expect to have to parse json from request bodies, // so we need the JSON middleware app.use(express.json()); // we will put our routes and controller functions here module.exports = app; ``` 1. Require your app in your `index.js` and call `app.listen()`: ```javascript // In index.js add this code: const app = require('./src/app'); const APP_PORT = 3000; app.listen(APP_PORT, () => console.log(`Cats app is listening on localhost:${APP_PORT}`)) ``` At this point, you should be able to run `npm start` in your terminal, and see that your app is listening to port 3000. Commit your work to git and change driver/navigator. ## Adding Sequelize For this next section, we will start adding routes and controller functions to our express app. First we want to focus on being able to send a `POST` request to `localhost:3000/cats` to create a new cat in our database. To get started, declare a `POST` route in `app.js` for `/cats`. Just have the controller return a `201` status and the request body for now. Hit the endpoint with a request from Postman to confirm that it is working. Now, lets bring `sequelize` into our app, so we can start saving cats in our database. 1. Create a new `models` directory inside your `src` directory. 2. Inside your `models` directory, create two new files, `cats.js` and `index.js`. Your project should now look like this: ```bash have-i-fed-the-cat-app ├── index.js ├── package-lock.json ├── package.json └── src ├── app.js └── models ├── cats.js └── index.js 2 directories, 6 files ``` 3. Inside `models/index.js`, require `Sequelize` at the top of the file: ```javascript // In models/index.js add this code: const Sequelize = require('sequelize'); ``` 4. Declare a function in the same file called `setUpDatabase`. Keep the function to empty for now. Invoke the function and export it's return value at the bottom of the file: ```javascript // models/index.js // ... const setUpDatabase = () => {} module.exports = setUpDatabase(); ``` 5. Inside your `setUpDatabase` function, declare a `const` called `connection` and assign it as a `new Sequelize()`: ```javascript // models/index.js ... const setUpDatabase = () => { const connection = new Sequelize("have_i_fed_the_cat_app", "postgres", "password", { host: "localhost", port: 5433, dialect: "postgres" }) } ... ``` 1. Next, still inside your `setUpDatabase` function, call `connection.sync({alter: true})`. This will allow changes to be saved into the DB. Finally, return an empty object from your function. Your complete `models.index.js` should look something like this: ```javascript // models/index.js const Sequelize = require('sequelize'); const setUpDatabase = () => { const connection = new Sequelize("have_i_fed_the_cat_app", "postgres", "password", { host: "localhost", port: 5433, dialect: "postgres" }) connection.sync({alter: true}); return {}; }; module.exports = setUpDatabase(); ``` This code will connect to our database and return `Models` that we can use to interact with our tables. Before we can do this though, we need to write a model for our `Cat` table. 1. In `models/cats.js` we want to export through `module.exports` an arrow function like so: ```javascript // In models/cats.js start by adding: module.exports = (sequelize, DataTypes) => {} ``` 2. Now we need to define a schema inside our arrow function: ```javascript // In models/cats.js continue defining the schema: module.exports = (sequelize, DataTypes) => { const schema = { name: DataTypes.STRING ... } } ``` Check the requirements for the other fields. Most of them will be `STRING` types, but one will need to be a `DATE`. 3. Have your function `return` `sequelize.define('Cat', schema)`. Your full file should look something like this: ```javascript // Your models/cats.js should look like this at the end: const { Sequelize } = require("sequelize"); module.exports = (sequelize, DataTypes) => { const schema = { name: DataTypes.STRING, breed: DataTypes.STRING, markings: DataTypes.STRING, lastFed: DataTypes.DATE } return sequelize.define('Cat', schema) } ``` Now that we have a model for our `Cat` table, we need to use it. Let's require it in `models/index.js`. 1. Inside `models/index.js`, require your `catModel` at the top of your file: ```javascript // models/index.js ... const CatModel = require('./cats'); ... ``` 1. Finally, inside your `setUpDatabase` function, after you have declared you `connection` but **before your have called `connection.sync()`**, declare `const Cat = CatModel(connection, Sequelize)`. Add your `Cat` to the object in your `return` statment: ```javascript // models/index.js ... const Cat = CatModel(connection, Sequelize); ... connection.sync({ alter: true }); return { Cat } ... ``` Now we are ready to wire up `Sequelize` to the rest of our app. You should use this opportunity to commit your work and swap driver/navigator. ## Saving a Cat in the database Now we are going to alter the controller function we have written in `app.js` so that it actually saves our cat data in our database. 1. In your `app.js`, requre `{ Cat }` from your models directory: ```javascript // In app.js require Cat model: const express = require('express'); const { Cat } = require('../models'); // ... ``` 1. Inside your `POST /cats` controller, call `Cat.create(req.body).then(cat => res.status(201).json(cat))`. Test your code with Postman by trying to make a cat. 1. Now create a `GET /cats` endpoint which return all the cats in your database. This will be similar to the code above, but this time you will be calling `Cat.findAll` rather than `Cat.create`. Use Postman to confim that your controller function works. 1. Now we want to create an endpoint to get information about a specific cat. This endpoint will be `GET /cats/:catId`. It will work almost exactly the same way as your `GET /cats` endpoint, but you will need to call `Cat.findByPk()` and pass it `req.params.catId`. This covers our `CREATE` and `READ` requirements for our app. ### Optional: Retrieve cats using query A nice feature you may wish to add is the ability to return all cats which match a `query`. To do this, simply pass into your `Cat.findAll({ where: req.query })`. This will let you add a `query string` to your `GET` request, and only return cats which match it. for example `GET http://localhost3000/cats?markings=tuxedo` will only return cats with tuxedo markings. ## Feeding the Cat In order to record the last time the cat was fed, we will need to implement a `PATCH /cats/:catId` endpoint. This again will be very similar to your other endpoints, but you will need to call `Cat.update(req.body, { where: { id: req.params.catId } })`. Test this new endpoint by trying to update the `lastFed` property for your cat. Note that `Postgres` `DATETIME` is formatted as `yyyy-mm-dd hh-mm-ss` ### Optional: Deleting a Cat With our app requiremnts we don't *need* to delete cats from the database, but it is one of the CRUD operations. Can you implement a `DELETE /cats/:catId` endpoint? You will need to use `Cat.destroy({ where: { id: ID_TO_DELETE } })` ### Optional: Easy Feeding The `PATCH` endpoint we just implemented can be used to update any part of our `Cat` record, including when they were last fed. This does however require the user to send a valid date string. To make things easier for the user, we could implement `PATCH /feed/cat/:catId` endpoint, where we specify that we are only updating the `lastFed` property and setting the timestamp ourselves. This will be very similar to our previous `PATCH` endpoint, but this time we want to pass it `{ lastFed: new Date() }` rather than `req.body`. ### Optional: Error handling All of the endpoints we have written assume that the data the user is supplying is always perfect. This is probably not going to be the case. Can you add `.catch()` blocks after your `.then()` to catch any errors and return a `400` status code to the user?

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully