Random Notes Flashcards

1
Q

Code reading for html-relative-links:

anchor tag href=”../about-me/about-me.html”

A

There is an opening tag for the anchor element and there is an href attribute with a value of a relative URL pointing to the about-me.html file within the about-me directory within the parent directory (..).

  • The forward slash is read as “within” and we start with the file we are trying to actually read (subject first)
  • We call them folders day to day, but it’s really called the directory”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Should you use divs or br to change up the document flow

A

Use divs to change document flow

br elements should only be used for breaking up text.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Do you need a label element for form control elements?

A

Not always. If there’s no text labeling the input area then you don’t need labels. You can just use placeholder attribute.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Code reading for CSS-colors

CSS selector { *background-color: rgb(244, 249, 251)}

A

we have a property with a CSS function, rgb, with the ARGUMENTS (244, 249, 251)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

CSS: How background-colors work?

thead
   tr
     th
   tr
thead
A

“Hey dude! Great question, that is because if you apply the styling to thead, the background color you are applying to the tr element will overlay that background color, and it would not be visible”

The child elements overlay the parent elements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

CSS: Code reading for pseudo class and descendants and children.

table.striped thead > tr:nth-child(odd)

A

A new css rule set with a selector for the tr element with a pseudo class (nth-child) with an argument odd which is a direct child of thead and is a descendant of the table element with a class striped.

TIP:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

CSS Layout control rules

A

Container should always be the external layer
Containers only hold rows
Rows should only hold columns

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Guide to make classes for HTML and CSS

A

Utility classes = named after the desired behavior. It’s made to be used multiple times, things that repeat. It should only have one or two things it does. They shouldn’t be changed. Instead make a new class with the desired behavior.

Semantic classes = named after what it’s holding. Add as last attribtute after all the utility classes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Two things container should always have?

A

Width or max width AND margin: auto;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the only thing that should be in the row class?

A

display: flex;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the only things in a column class?

A

Only width

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Position absolute has to be a child of relative.

A

Most of the time, but not always.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Width:100% or offset properties of top, bottom. right. and left set to a value of 0?

A

Both work.

Offset values of 0 will make it take all available width.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Primary use of absolute positioning?

A

If you need to layer something on top of something else.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

CSS Layout classes for row, column, and container.

A
Row = display flex;
column= width
container = width (with hard px val) and margin auto
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

JavaScript code reading:

console.log(‘value of:’, typeof fullName);

A

the log method of the console object is being called with two arguments, the string, value of, and the result of the expression typeof fullName

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

JavaScript code reading ‘.’ is read how?

How is vehicle[‘color’] = ‘white’ read?

A

the dot (period symbol) is read as of

the string white is being assigned to the variable vehicle at string color (brackets are read as ‘at’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Good thing to note about objects and primitive data

A
var me = {name: "john", age:"20"};
undefined
var otherMe = me
undefined
otherMe.name = 'chad'
'chad'
me
{name: 'chad', age: '20'}
var a = 1
undefined
var b = a
undefined
var a = 12
undefined
a
12
b
1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Square brackets [ ] =

Curly brace { } =

A

square is for array literal

curly brace is for object literal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Data Modeling, think about data what you need and how to store it

A

It’s best to create a diagram or something to plan out the data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a javascript expression?

A

Chunk of code that is being evaluated and returning a value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

JavaScript code reading:

function convertMinutes(minutes) {
  var seconds = minutes * 60;
  return seconds;
}

var convertMinutes = convertMinute(5);

A

a function is being defined with the name convertMinutes with one parameter named ‘minute’

the value of minutes is being multiplied by the number 60 and the result of that expression is being assigned to the variable seconds

the variable seconds is being returned FROM the function.

the function convertMinutes is being called with one argument, the number 5, the return of that function call is being assigned to var convertMinutes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

CSS E-commerce challenge (due Monday, probably can be done by Friday)

A

strikethrough element? s

background color on current price

LV picture is a different sized picture on purpose (challenge)
object-fit (css property) - useful to adjust height/width without messing up aspect ration on images

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How to read:

var something = math.floor(randomValues)

var firstBook = library.shift();

A

the floor method of the math object is being called with one argument, the variable randomValues and the return of that method is being assigned to the variable something

the shift method of the library object is being called with no arguments and the return of that method is being assigned to the variable firstBook

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

JavaScript If Code reading:

function isUnderFive(number) {
  if (number > 5) {
     return true;
} else {
     return false;
}
A

there is a function being defined with the name isUnderFive, with one parameter NAMED ‘number’ and then the opening curly brace for the function code block. We have an if statement with the condition ,variable number is greater than 5. then opening curly brace for the if statement.

the boolean value true is being returned from the function
the boolean true is being returned from the function
closing curly brace for the if statement,

Note that from “if” to the closing curly brace is the “conditional”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

JavaScript for loops code reading: for (var i = 0; i < string.length; i++)

for (var key in object) {
keys.push(key)
}
return key;

A

for loop with an initialization of the number 0 being assigned to the variable i, a condition of i being less than the length property of the string object, and a final expression of the variable i being incremented by 1

for in loop with the var key in object, object then opening

push method of the keys object is being called with one argument the value of variable key

value of the variable key being returned from the function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

@media rule code reading

@media only screen and (min-width: 768px) { 
  .card-wrapper {
      flex-basis: 50%;
  }
}
A

There is a new @media rule for only media type screen and a media feature of min-width: with a value of 768px followed by the opening curly brace for the @media rule set. Then read as normal

*Note: min-width in the @media rule is not a property, it is a media feature

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Template literal code reading

const hello = `Hi my name is ${firstName}

A

There is a template literal with (just say the string as if reading) with a javascript expression, with the value of the variable firstName, and the result of that expression is being assigned to variable const hello.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

es6-destructuring code reading

const { title, author, libraryID } = book1;
const [book3, book4, book5] = library;
const [, , , book6] = library;

A
// if it's an array you say 1st, 2nd, 3rd element is being destructured
    // if it's an object you say properties names
// third option just say it's the 4th element
    // Code Reading for destructuring:
    // 1. What is being destructured
    // 2. Where is it being destructured from
    // 3. Where is it being assigned to
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Library vs framework

A

Answer is that all libraries are frameworks, but not all frameworks are libraries. Frameworks have inversion of control

all libraries are frameworks, but not all frameworks are libraries (called inversion of control - who calls who)

  • Using framework if you define functions, but never call them (some exceptions) instead hand them over it means your library is a framework (DOM is a framework for the events)
  • If library has a bunch of functions and methods, and your code calls it then it is just a library

Gray area exists (meaning it could be more library-heavy or library-light).

Node.js is a runtime environment that comes with a library

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

If you convert an object into a string, what does it return

A

it returns object Object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

node-require example answers

subtract function which is exported

A
function subtract (x, y) {
   return x - y;
}

module.exports = subtract

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

node-require code reading

const add = require(‘./add’);

console.log(‘result:’, add(x, y));

A

the require function is being called with one argument, a string, and the return of that function is being assigned to the variable const add

the log method of the console object is being called with 2 arguments, a string and the RETURN of the function add with two arguments, x and y

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

four major concepts of JavaScript

A
  1. prototypal inheritance
  2. how ‘this’ works
  3. closures
  4. the event loop
35
Q

node-require example answer for calculate.js

A

assigned process.argv[2] and process.argv[4] are assigned to a variable which is called in the functions

Used parseFloat to have decimals instead of parseInt which is just an integer, but using Number() method might be better

so ex: 
const x = parseFloat(process.argv[2])
const operation = process.argv[3] --- this stands for the middle word like 'plus' or 'minus'
const y = parseFloat(process.argv[4])

add(x, y)

36
Q

node-fs-readfile sample answer

read-any.js

A
// Enable interaction with the file system
const fs = require('fs');
// Assigning user input into a variable
const filename = process.argv[2];
// asynchronously reading the contents of the file
// and encoding it using the utf8 character set
fs.readFile(filename, 'utf8', (err, text) => {
  // Check if there was an error while reading the file
  if (err) {
    // if there is an error
    console.error(err); // write the error to the process's stderr
    process.exit(1); // forcibly quit with a failure code (not 0)
  }
  console.log(text); // otherwise print the file content to stdout
});
37
Q

node-fs-readfile: When not using ‘utf8’ = Buffer terminology

A

binary: 0 or 1 -> base 2
bit: binary integer (literally just represents binary)
byte: 8 bits
decimal: 0, 1, 2, 3, 4, ,5, 6, 7, 8, 9 -> base 10
number base: how many different digits/ characters you have available to represent numbers
hexadecimal: a-f, 0-9 -> base 16

  • Without ‘utf8’ in readfile method then the text is raw bytes data which is converted into hexadecimal data*
    ex: 6d = ‘m’ = m.toString(2) will show binary code
38
Q

http-messages-recap

content-type

A

Responsible for how the data is shown/displayed

39
Q

npm-intro

A

packages have packages.json files

packages.json is not a package, it’s just a file

40
Q

npm-intro

Rules before installing packages

A
  1. check if the GitHub link works so ou can review if code is sketchy
  2. Proper documentation
  3. Popularity - is it frequently used? (check weekly downloads)

DISCLAIMER: anyone can publish packages on npm

41
Q

express-get-json

app.METHOD is the same as what?

A

It is the same as an add event listener, which means app.METHOD is called once, but its callback arrow function is called numerous times when the METHOD is called.

42
Q

express-post-json

app.post ex:

A

const jsonMiddleware =express.json()

app.post('/api/grades' function (req, res) {
  // grab request body
   const newGrade = req.body
 // get current 'nextId' value and increment it for next time
   const id = nextId++
// take current id and assign to new grade var
   newGrade.id = id
// store complete new grade in data model
   grades[id] = newGrade
// respond to client with the obj we stored and a created status code
  res.status(201).json(newGrade)
}
nextId = 1
// don't need to adopt this style of incrementing, not needed
Notess: const id = nextId

using id var is current value so 1
But if you call id after then it uses value 2

43
Q

express-post-json

method chain code reading

res.status(201).json(newGrades)

A

the status method of res obj being called with 1 argument, then the json method of the return of the status method being called with 1 argument newGrades
It so happens that res.status(201) returns res obj

similar to string.toUpperCase().split()

44
Q

express-json

Does the route lead to folder or file?

A

No it doesn’t have to, it is just telling the server the route to access.

45
Q

Full Stack Developer = 3 Tier Architecture

Casual term vs professional term

A

Back end = Web/HTTP Servers
Front end = Browsers/Client software
Databases = DBA (Database Administration)

Note: LFZ learning breakdown (30% backend, 60% frontend, 10% databases). Most likely end up getting a job in front end because we learn enough back end to become a better front end developer. Can still get a job in back end, but prob not full stack.
Only learning how to use database, what a database is, and how to integrate it into your app.

46
Q

More Full stack

A

Full-stack

  • Client (browser)
  • Server (node.js / express)
  • Database (PostgresSQL)
  1. client sends request to the Web Server (request)
  2. Server receives the request (request)
  3. Server sends a query to the database (INSERT a new row)
  4. Database replies to the server with a ‘result’
  5. Server can now send a response to the client

Note: Client and Server are RELATIONSHIPS (not things)
- The ‘server’ is a ‘client’ of the database.

47
Q

PostgreSQL documentation reading tip

A

brackets [ ] means it is optional
curly braces { } means you have to pick one
parenthesis ( ) means you have to have them if you choose that option

48
Q

pgweb query tab

A

You can use the explain query/analzye query by the run query button to see query logic

49
Q

PostgreSQL backup

A

In terminal, pg_dump pagila > pagila.backup.sql

pagila is just the sample db name

50
Q

PostgreSQL transactions

should always use psql dbName to enter env in terminal????

A

commands:

‘begin;’ starts a transaction - it lets you do any statement without client seeing till you’re finished (think of it as a branch)

can use ‘rollback;’ to undo transaction

or ‘commit;’ to make changes for everyone

just use ‘begin;’ on its own line

don’t use pgweb to manipulate data

51
Q

use cases for join clause

A

for favorites

52
Q

With statement postgresql

A
with "actorFIrstName" as (
select 'firstName' as 'name'
from 'actors'
),  'actorLastName'. as (
select 'lastname'
from 'actors
)
select 'name', 'surname'
from 'actorFirstName'
join 'actorLastName using('actorId')
limit 5

can use subqueries too (select statements inside ‘from’ clause)

53
Q

es6-promise differentiation from fs.readfile callback

A

promise guaranteed to run error and then callback ONCE, but readfile can have bugs by devs which cause the callback to get called twice.

promises takes away ‘callback hell’

54
Q

filter function

A

It’s a synchronous function so the ‘callback’ parameter is really a ‘predicate’ since it’s called on the stack right away

Note: It substitutes for loops

actually slower than regular function with loops and conditionals because filter placed on stack, THEN predicate is placed on and off stack over and over till end of array.

May be useful for search engines/bars

55
Q

Research passed by reference (immutability), this affects arrays and objects

A

array1 = array2, makes it so array1 === array2

const array2 = array1.slice(), makes it so array2 is a ‘shallow copy’

obj1 = obj2, is ===

for shallow copy of object use ‘Object.assign({}, obj1)’

56
Q

reduce function tips for naming parameter

A

name ‘previous’ parameter to what the return value would be identified as, so like ‘balance’ for bank accounts

name ‘currentVal’ parameter to what the thing in your input array is, so ex: is transaction for an array of transactions

Note: can recreate map and filter with reduce method… reduce is the most general and most powerful

57
Q

Useful array methods Tim uses other than map, filter and reduce

A

find(), forEach(), reduceRight(), every() (REALLY GOOD - checks if everything in array has predicate func return to true), some()

58
Q

es6-classes

code reading classes

class Student {
  constructor(firstName, lastName, subject) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.subject = subject;
  }

getFullName() {
return ${this.firstName} ${this.lastName};
}

  getIntroduction() {
    const fullName = this.getFullName();
    return `Hello, my name is ${fullName} and I am studying ${this.subject}.`;
  }
}
A

new class definition named student with the opening brace for the class body

Each function lookalike is actually a prototype method being defined named ‘constructor’ with 3 parameters

59
Q

Visualization of classes/constructors

A
function createStudent() {
  return {
    fullname: function getFullName() {},
    introduction: function getIntroduction() {}
  };
}
60
Q

Check out MollyRocket on youtube

A

https://www.youtube.com/watch?v=Ge3aKEmZcqY

61
Q

react-jsx

code-reading

const element = <h1>Hello, JSX!</h1>;

ReactDOM.render(
element,
document.querySelector(‘#root’)
);

A

creating react element of TYPE, h1, with CHILDREN, ‘hello, jsx’, and the result of the expression is being assigned to the const variable element

the render method of the ReactDOM obj being called with 2 arguments: the value of the variable element and the return of the querySelector method of the doc object being called with one argument, string hashtag roo

Note: angled brackets means it is a react element

62
Q

react-props-and-expressions

code reading:

import React from ‘react’;
import ReactDOM from ‘react-dom’;

function CustomButton(props) {
  return (
  {props.text}
  );
}
const element = (
  <div>

</div>
);

ReactDOM.render(
element,
document.querySelector(‘#root’)
);

A
  • Importing react from the react package
  • Importing reactDOM from the react-dom package
  • There’s a function being defined named Custom Button with one parameter, props, opening curly brace
  • The result of an expression is being returned from the function with 1 argument, the React Element of type button with children, the result of the JSX expression, text property of the props obj,
  • The render method of the ReactDOM object is being called with two arguments, the variable element, and the return of the queryselector method of the document obj being called with 1 argument, the string #root
63
Q

Setting up React environment

A

npm installs:

Dependencies
1. npm init -y
2. npm install react react-dom
Dev Dependencies:
3. npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/plugin-transform-react-jsx

npm scripts:

  1. “build”: “webpack”,
  2. “watch”: “webpack –watch –mode=development –devtool=source-map”,
files:
mkdir src
mkdir dist
touch dist/index.html (Make div#root and link script with src="main.js")
touch src/index.jsx
touch webpack.config.js

paste into webpack.config.js:

module.exports = {
resolve: {
extensions: [‘.js’, ‘.jsx’]
},
module: {
rules: [
{
test: /.jsx?$/,
use: {
loader: ‘babel-loader’,
options: {
plugins: [
‘@babel/plugin-transform-react-jsx’
]
}
}
}
]
},
performance: {
hints: false
}
};

Use npm run build to load page once

Use npm run watch to have continuous reloads on save (along with live server)

64
Q

react-events-and-state solution w/ explanation

A
import React from 'react';
import ReactDOM from 'react-dom';
​
class CustomButton extends React.Component {
  // FIRST instantiate a CustomButton object from this class - ONE TIME
  constructor(props) {
    super(props);
    this.state = {
      isClicked: false // establish an initial state
    };
    this.handleClick = this.handleClick.bind(this);
    // create a bound copy of the prototype method handleClick
    // assign the bound copy to an "own" property of this object
    // with a permanent "this" to guarantee the value of "this" when it's called
  }
​
  handleClick(event) {
    // ONLY decide how to update state by calculating a new state
    event.target.className = 'tim will kill you'; // NO, you're fired.
    // Tell React which state propert(y|ies) to replace
    this.setState({ isClicked: true });
    // please transition to a new state
    // schedules a re-render with a new state (render will be called again)
    // Add a toggle version...
  }
​
  // 2. React _immediately_ calls the render method after the constructor
  //    Will re-run when this.setState() is called in the future
  render() {
    // ONLY decide how the UI should look
    /**
     * DON'T
     * - manipulate the DOM
     * - update global variables
     * - use timers
     */
    if (this.state.isClicked) {
      return Thanks!; // add an onClick prop for toggling if desired
      /**
       * {
       *   type: 'button',
       *   props: {
       *     children: 'Thanks!'
       *   }
       * }
       */
    }
    return {this.props.text};
    /**
     * {
     *   type: 'button',
     *   props: {
     *     onClick: this.handleClick,
     *     children: 'Click Me!'
     *   }
     * }
     */
  }
}
​
ReactDOM.render(
  ,
  document.querySelector('#root')
65
Q

General strat for react even listeners

A

General strat for event listeners:

  • Decide how to update state, most likely don’t have loops, it’s mainly conditionals
  • IE don’t use it to manipulate the DOM, React owns the DOM

General strat for render:
- Decide how the UI should look

66
Q

How to get auto updating node.js server

A

npm install –save-dev nodemon

“scripts”: {
“dev:server”: “nodemon index.js”
}

npm run dev:server (to keep server on)

67
Q

Command line tips

A

touch src/{index, hot-button}.jsx - adds multiple files (2)

command ‘tree’ directoryName shows tree of folder

68
Q

React website building (hot-button)

A
  1. define component
  2. make render() first and just print something to page (don’t make constructor and handlers first)
  3. Now make constructor to establish state for the component
    tip: use react dev tools instead of console.log bcuz async so might console.log wrong place and receive false data.
  4. define css classes for the different button colors, but don’t add styling
  5. set up render logic, naive way = if/else statements, and add classNames
    tip: turn off autosave in VS Code and have terminal to see build output by webpack and have browser visible for live reload too
    Another tip: you can click on react dev tools to change state/props manually so like 4 clicks instead of 0
    Tip: It is smart to mock DOM in HTML, but it’s better to just start mock up in render method of the component. that way you’re using react more
  6. Add CSS styling
    Note: we haven’t added in event listeners yet, it’s more important to do the mockup THEN add behavior aka clicks later
  7. Start adding handler functions. (logic: console.log() something to make sure click is registered, add variable that reads the current state, add variable that calculates new state, and then replace current state) with this.setState - DON’T change original values with push() or ++. Event listeners should never return something explicitly.
  8. bind event handler functions
  9. Test functionality
  10. to solve naive way: identify what’s different about each one, in this case it’s just className.
    - You can just add if/else before the return statement, so make a className var and only have to write one react element (viable for 1-3 things that are different)
    - Better way if changing a lot of stuff like this then make a function outside the render method then add our function with a JavaScript expression.

How to describe in interview:

  1. when program starts we mount the component aka HotButton
  2. in that component we test this condition
  3. then render the react element based on that info

Important note: don’t need handler function logic to test functionality, you can update state manually with reactDevTools or constructor state.

Big NOTE: check code often and do everything in steps, shouldn’t have 50 lines of codes and page doesn’t run

69
Q

Limited breakdown of static middleware

A
function createStaticMiddleware(directoryPath) {
  return (req, res, next) => {
    const filePath = req.url; // ex: styles.css
    const absoluteFilePath = path.join(directoryPath, filePath);
    fs.readFile(absoluteFilePath, 'utf8', (err, fileContent) => {
      if (err) {
        next(err);
     } else {
       res.send(fileContent);
  }
}
70
Q

ternary expression reading

A

ternary expression with the condition this.state.isLoading, if truthy the result is a react element of type p with child text loading… and if falsy reactelement userlist with props users with a value of a javascript expressioon

result of the ternary expression being returned from the render function

note 3 types: binary (+ = - >), unary (++ – !), and ternary (3 things: condition, truthy, or falsy)

71
Q

Interview question for react job

A

Do you know the react component life cycle?
Basic answer:
1. constructor needs to run ONCE for entire life cycle of component
2. then render()

*look up virtual dom vs real dom (probably another question)

  1. then componentDidMount() if it is defined (called on first successful render)
  2. then time passes, if setState is eventually called then it triggers a re-render which runs the render method again
  3. ComponentDidUpdate() will be called after every subsequent render from first
  4. ComponentWillUnmount

Basically asks when these things are called.

72
Q

lifting state up brief explanation

A

share data b/w two components that aren’t parent/child

pass state as a prop

73
Q

‘throw’ keyword

A

It throws EVERYTHING off the call stack.

In the case of express it throws then the express middleware catches it and handles the error based on default or if custom error function deifned

74
Q

Meanings of json() in different techs

A

.json() ::::

 - express.json() create a json-parsing middleware (server)
 - res.json() in Express responses - send a JSON response (server)
 - res.json() in fetch responses - download and parse a JSON repsonse (client)
75
Q

argon2

.verify(hashedPassword, providedPassword)

A

verify returns a promise for the password if the arguments match (a boolean), after that we can access the hashedPassword with:

.then (result => {})
result is the hashedPassword we receive from .verify()

so the then() method’s arrow function parameter, after a ‘promise’, should be whatever the data is returned by the promise

76
Q

payload and jwt.sign (json web tokens)

A

payload is anything that can be turned into JSON so objects and arrays and is turned into base 64 token with .sign()

TOKEN_SECRET (the signature) is a ‘password’ for the server to verify the password - basically encryption of ORIGINAL payload

    • each login gives a new token
    • token is used to identify the user

resource link: https://jwt.io/#:~:text=the%20client%20side.-,Algorithm

77
Q

what does import ‘dotenv/config’ do?

A

it pulls all the key/value pairs from the .env file and makes it a property on the process.env object. That way you can use process.env.EXAMPLE to access that key name/value

having .env.example means people can easily clone your repo
It also lets us deploy our project on a server easily without using variables/parameters specific to your local pc

78
Q

How middleware works

A

This example is related to api-authorization: it is why the function authorizationMiddleware can reassign req.user to payload and we can use that assignment in the app.post in index.js

Middleware pokes into the req, res, etc. of the http request

It goes in order from top down, so it matters when app.use(someMiddleware)

79
Q

how to look at destructuring

const { name } = person.name???

A

const person = { name: hello }

const name = person.name

80
Q

how to find props in react?

A

Go to current class name then right click and find by ‘reference’

81
Q

React special props: ref, key

A

index.js for react-file-uploads

purpose of ref is a way to poke a hole through to the real DOM since React is fully in charge of dom.

It sticks a reference of the REAL DOM element so that you can use and access DOM info just like vanilla JavaScript (Tim said it’s used for handing over DOM elements to another library.)

In this case we are using it to access the files property of image inputs so that we can get the actual file of the upload (the event.target.value isn’t enough info)

It’s a case of React’s virtual DOM and the REAL DOM

Another example: In a chat app you’d need a ref for the div box of the chat and access the scrollTop of the DOM element, which React can’t do.

Note: database isn’t storing the image itself, it’s storing the location of the image

82
Q

TO style file inputs (NVM)

A

Maybe hide the actual fileee

83
Q

DbDesigner (typed with camel case)

A

IT DOESN’T autosave

  1. new project
  2. create table
  3. name table based on main topic
  4. add field (‘text’ for strings and don’t allow ‘null’ for photos)
  5. photoId = serial (unique identifier w/ primary key and auto increment) Put ID on top of table
  6. uploadedAt = timestamp with time zone (nothing checked)
  7. foreign key means it’s a reference to another table (ref to table and ref to specific column - draws an arrow) - foreign key should be integer
  8. unique key for usernames (don’t mark as unique, just use text, for hashedPasswords)
  9. ‘point’ type is for storing latitude
  10. ‘allow null’ means form isn’t required
  11. don’t ask for email if not needed
    Tip: usually an object (data model) means it’s a table
  12. serial is for the column that identifies the table
  13. Attaching photoId and userId in likes table checks for if someone liked a specific photo (don’t autoincrement foreign keys)
  14. when done ‘export’ with create script (warning BUG- it should be “public” . “photos”, NOT “public.photos”) - PASTE this below ‘create schema “public”; in the schema.sql
  15. if error or want to add to database, then you should edit in dbdesigner and then export and repaste that into schema file (NOTE: it will delete all existing data)

use db:import and then ‘dev’ script