# 2003-GHP Cookie Jar: Sequelize
Put your pending and outstanding questions here 👇
Make the question in an H2 tag by using '##'
Example:
## What is JavaScript?
## What does it mean when you declare a variable with brackets like in the following example: "const [user, wasCreated] = ..." ?
## Answer
This is called `array destructuring`. You've seen this kind of syntax before with `object destructuring` (i.e., `const { something, something2 } = require('./someFile')`. And if you remember, it's shorthand from doing something like this:
```javascript=
const someStuff = require('./someFile')
// Later on in the file
somestuff.something()
somestuff.something2()
```
Instead with `object destructuring`:
```javascript=
const { something, something2 } = require('./someFile')
// Later on in the file
something()
something2()
```
With `array destructuring`:
```javascript=
const [a, b] = ['cool', 'beans']
console.log(a) // cool
console.log(b) // beans
```

[MDN: Destructuring Assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
## Im having trouble understanding the structure of the project when using routes, it becomes really confusing. Like which pages need to require each module if they contain a route, etc.
I will go over this in morning review and put it in here afterwards.
So, if you mean, using `Express Router` to modularize our routes, let's take a look more into `Express Router` briefly. It's a piece of middleware, so it gets called in between the request and response to know which endpoint to send the request to.
So, let's take a look at our folder structure in wikistack.
`routes/wiki.js`
The main things to look at are these lines:
```javascript=
const express = require("express");
const router = express.Router();
```
which initializes the routing middleware so we can start using `router.get()`
and this final line:
```javascript=
module.exports = router
```
which is saying that we want to export this router file.
The logic follows the same way in `routes/users`
In `app.js`,
We have these lines:
```javascript=
app.use(morgan("dev")); //logging middleware
app.use(express.static(path.join(__dirname, "./public"))); //serving up static files (e.g. css files)
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use("/wiki", require("./routes/wiki"));
app.use("/users", require("./routes/users"));
```
Which is letting us start using the middlewares. Specifically looking at the last two lines, we are saying that we want to use the routing middleware.
In the final line of that file, we have:
```javascript=
module.exports = app
```
which is being `required` in `server.js` to initialize our Express app.
In regards to figuring out what pages need to be required,
In `routes/user.js` we are using views related to user and `routes/wiki.js` and views related to pages
## In the add form in Wikistack, when we click the submit button, it adds data to DB. Where is the eventListener written for it? I was unable to find it
Inside the views folder, there is an `addPage.js`. Let's take a look at the format of the form.
```htmlmixed=
<form method="POST" action="/wiki/">
...
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">submit</button>
</div>
```
At the top, we have say that the form will do a POST request (using the `method` attribute) and the `action` attribute is telling the form where to go, in this case, our POST route to add to the Wiki
At the bottom, the button type of submit which will function as it sounds: submit the form data as a POST request to the specified route.
- [HTML Form Method Attribute](https://www.w3schools.com/tags/att_form_method.asp)
- [HTML Button Type Attribute](https://www.w3schools.com/tags/att_button_type.asp)
## What is the difference between
let page = new Page()
page.save();
and
let page = Page.create();
Both the methoda were mentioned in the workshop yesterday, but I am not clear when to use which one?
## Answer
Great question. So, Sequelize, when it creates or updates a model, goes through a process.
When we do .create(), it goes through a:
1. build() process. Note build() is a function in Sequelize
2. save() process
The build() process creates a new instance but does NOT save it. Once .create() finishes the .build() process, it calls .save()
So, you'd call .save() probably when you're doing some sort of update. You'd call .create() when you're trying to create new info.
## Is setAuthor() some predefined function in Sequelize?
Great question. So, remember the Sequelize `magic methods`, I briefly talked about yesterday? When we create associations using `belongsToMany`, `belongsTo`, `hasMany`, `hasOne`, we get magic methods?
More Info in this [gist](https://gist.github.com/jbracht/1778e93ced532b902fc49d70a743ffb8)
In the `models/index.js` file we create an assocation:
```javascript=
Page.belongsTo(User, {as: 'author'});
```
Because we created above, the `belongsTo` has accessor (magic) methods below (You can see more information in the gist above):
```javascript=
this.accessors = {
get: `get${singular}`,
set: `set${singular}`,
create: `create${singular}`
};
```
So, then it becomes for us:
```javascript=
this.accessors = {
get: `getAuthor()`,
set: `setAuthor()`,
create: `createAuthor()`
};
```
So then in `routes/wiki.js` where we have the piece of code:
```javascript=
const page = await Page.create(req.body);
await page.setAuthor(user);
```
`setAuthor()` is recognized
# Why is this res.status() above the res.json(await ...)?
Does the order matter here? Any benefits to placing it above the res.json instead of below? (As opposed to the DELETE route where it is placed under the "await workout.destroy"?)
Also, is there a reason for using .status() over .sendStatus() - or vice versa?
```javascript=
// POST a new workout
router.post('/', async (req, res, next) => {
try {
const { name, date } = req.body
res.status(201) //
res.json(await Workout.create({ name, date }))
} catch (err) {
console.error(err)
}
})
// DELETE a workout by id
router.delete('/:id', async (req, res, next) => {
try {
const workout = await Workout.findByPk(+req.params.id)
if (!workout) return res.sendStatus(404)
await workout.destroy()
res.sendStatus(204)
} catch (err) {
console.error(err)
}
})
```
## Answer
(1) Order technically doesn't matter here but it is better to put that line after we are done creating.
(2) `status` sets an HTTP stats on the response; `sendStatus` both sets the status AND sends it to client. You would use `status` if you want to send something else along with the status. Ex:
```javascript=
res.status(201).send(`I just created something!`)
```
## What is a hook?
Every Sequelize Model instance has a lifecyle of which they are created, updated and destroyed.
Think about after a simple JavaScript function runs, it gets put into the call stack, it designates some memory (execution context) to be able run whatever is in the function and then after it's done, it gets popped off the call stack and then the memory of it gets released.
There are a four lifecycle events that an instance can go through:
- Validate
- Create
- Destroy
- Update
And Sequelize has default methods that allows us to *hook* into these lifecycle events.
We can define some logic in these methods to be able to do something with our instance before or after we save/create it in our database.
For more information, check out Julissa's [Amazing Gist](https://gist.github.com/Julissa93/6a6d29874d34a801d603d2522645025f)
## In the example below, why is Coffee capitalized and does the table name 'coffee' have to be pluralized?
I'm unsure of when Sequelizes auto-pluralizes.
## In the link below (Your First Model section), why can we use await without async?
https://sequelize-guides.netlify.com/getting-started/#your-first-model
## When would you use beforeSave vs beforeCreate hook?