All Flashcards
URL stands for?
Uniform Resource Locator
Amazon’s full secure home URL
https://www.amazon.com
HTTPS stands for?
Hypertext Transfer Protocol Secure
The command to generate a React project inside the current directory.
npx create-react-app ./
Install command needed to use SASS
npm install node-sass
HTML stands for?
Hypertext Markup Language
CSS stands for?
Cascading Style Sheets
BEM stands for?
Block Element Modifier
In the URL, https://www.amazon.com/home
What is the ‘amazon.com’ part called?
Domain
In the URL, https://www.amazon.com/home
What is the ‘/home’ part called?
Path
IP Address stands for?
Internet Protocol Address
What is 104.59.62.31 an example of?
IP address
An IP address is a network device’s ___ ___.
unique identifier
DNS Server stands for?
Domain Name System Server
PEMDAS stands for?
Parenthasis Exponent Multiplication Division Addition Subtraction
Acronym used to represent the order of math operations in Javascript
PEMDAS
REPL stands for?
Read Evaluate Print Loop
Acronym used to represent console operations.
REPL
List of JS falsy values.
false, 0, “”, null, undefined, NaN
false, 0, “”, null, undefined, NaN are Falsy values.
All other values are __.
Truthy
The “for of” loop works on ___ like arrays and strings.
itterables
The “for in” loop works on ___.
objects
CORS stands for?
Cross-Origin Resource Sharing
Give HTML comment with “some msg” inside.
HTML5 declaration tag
Default shortcut key to toggle Word-wrap mode in VSC.
alt + z
What are the Font Awesome Icon types for fas, far, fal, fab, fad, in that order.
solid regular light brand duotone
Font Awesome icon to make svg 3 times larger.
fa-3x
# fill in the blank: \_\_\_(255, 255, 255, 0.4) returns a transparent shade of white
rgba
f00
red
0f0
green
00f
blue
fff
white
000
black
ff0
yellow
f0f
fuchsia or magenta
0ff
cyan or aqua
What is the hex code for the HTML color ‘green’?
008000
0f0
line
box-shadow: 2px 2px 2px 2px rgba(0,0,0,.5)
What are these values called from left to right?
horizontal offset
vertical offset
blur
radius
color
List all of the functions available for the CSS filter property.
blur()
brightness()
contrast()
drop-shadow()
grayscale()
hue-totate()
invert()
opacity()
saturate()
sepia()
url()
Return a random number from 0 to n (inclusive) using Javascript.
Math.floor(Math.random() * (n + 1))
Return a random number from 1 to n (inclusive) using Javascript.
Math.floor(Math.random() * n) + 1
Return a random number from 0 to n (excluding n) using Javascript.
Math.floor(Math.random() * n)
Return a random number from m to n (inclusive) using Javascript.
Math.floor(Math.random() * (n - m + 1)) + m
Convert the Grinning Face Emoji’s Unicode number (U+1F600) into an HTML entity DECIMAL code.
Hint: 1f600 hex = 128512 integer
😀
& # 1 2 8 5 1 2 ;
Convert the Grinning Face Emoji’s Unicode number (U+1F600) into an HTML entity HEX code.
Hint: 1f600 hex = 128512 integer
😀
& # x 1 f 6 0 0 ;
ALT codes without leading zeroes (ALT nnn) produce characters & symbols based on IBM Code Page 437 / DOS (codes 0 - 255)
Note: Most do not correlate with their Unicode hex value
reminder
ALT codes with leading zeroes (ALT 0nnn) produce characters & symbols based on Windows Code Page 1252 (codes 01 - 0255)
Note: The decimal code can be derived from their Unicode hex value
Note2: These are a strict superset of ASCII wherein the first 128 codes are ASCII
reminder
Convert the Grinning Face Emoji’s Unicode number (U+1F600) into a CSS string escape value.
ie
.someClass {
content: ‘emoji here’
}
/1f600
Website for Emoji codes
emojipedia.org
VS Code Extention to lookup and insert emojis in their single character format using intellisence.
ie
:emojiName
Emoji Snippets
VS Code Extention to lookup and insert an emoji’s encoded string according to the current file’s language type.
ie
ji:emojiName
Emoji Code
Windows shortcut key to open Emoji Picker
Win + period(.) or Win + semicolon(;)
Given the below functions in a single file, how can you export all of them with the ‘helpful’ function being a default, in TWO lines of code.
const helpful = () =\> some code const sayHello = () =\> some code const listFoods = () =\> some code
export default helpful
export {sayHello, listFoods}
Given the below export declaration in the “./test.js” file. How would you import all of its functions?
export default helpful
export {sayHello, listFoods}
import helpful, {sayHello, listFoods} from ‘./test’
What does ‘000045’.slice(-3) return?
‘045’
const randNum = Math.floor(Math.random() \* 1000) Use the .slice() array function and string litteral notation to return the random number as a string padded with zeros (ie '004' or '051')
00${randNum}
.slice(-3)
\00765.slice(-3) -> ‘765’
\004.slice(-) -> ‘004’
A way to declare default props on a Class or Function based component.
Call FuncOrClassName.defaultProps = { …someProps } before exporting.
POJO stands for?
Plain Old Javascript Object
setState() (class based version) with function callback that takes two params.
setState((prevState, props) =\> { //some code return newStateObject //the new object only needs to contain the //updated properties } )
when using ‘this’ INSIDE of a function defined inside of a Class, the caller that later executes the function, loses the ‘this’ reference to the class (‘this’ becomes undefined, instead of pointing to class instance).
You can use the following to fix the reference to this:
1. in the class constructor:
this.someFunction = this.someFunction.bind(this)
2. when executing/when called:
call-> this.someFunction.bind(this)()
3. use an arrow function to define the function or execute the function within an arrow function
reminder
The arrow function binds ‘this’ to context of the object it was defined in, rather than the context of the object it’s called on.
reminder
Command to install FontAwesome Pro
npm install @fortawesom/fontawesome-pro
Command to install FontAwesome Free
npm install @fortawesom/fontawesome-free
In order to use FontAwesome PRO globally, what two npm commands need to be run?
npm config set “@fortawesome:registry” https://fontawesome.com/
npm config set “//npm.fontawesome.com/:_authToken” myProTokenId
Filename to create in a project to use FontAwesome PRO, locally.
.npmrc
What should be added into an local .npmrc to use FontAwesome Pro locally
@fortawesome:registry=https://npm.fontawesome.com/ //npm.fontawesome.com/:\_authToken=MyProAuthToken
Import statement to include FontAwesome PRO
import ‘@fortawesome/fontawesome-pro/js/all’
What are 4 special CSS properties to style the color and opacity of Duo-tone FontAwesome icons
- -fa-primary-color
- -fa-primary-opacity
- -fa-secondary-color
- -fa-secondary-opacity
Class name to reverse the primary and secondary opacity for a FontAwesome Duotone icon?
fa-swap-opacity
With FontAwesome you need to import css instead of js when you need to dynamically change which icon is used via className.
This is because the JS file generates and inserts an SVG. You rendered SVG doesn’t change based on className. An it seems the script that generates the SVG is compile time.
The CSS version of FontAwesome inserts a Unicode character which is inserted via the CSS class name. So you can dynamically swap out the icon via class name.
reminder
CSS property and value (property: value;) to make a square element circular.
border-radius: 50%;
A simple Math.random function/equations that returns True 25% of the time.
Math.random() < .25
A simple Math.random function/equations that returns True 72% of the time.
Math.random() < .72
A simple Math.random function/equations that returns false 65% of the time.
Math.random() >= .65
CSS property: value to give only the bottom right of an element a 10px radius.
border-radius: 0 0 10px 0;
CSS property: value to give only the top left of an element a 15px radius.
border-radius: 15px 0 0 0;
A function to control multiple input fields with one handler. (controlled inputs)
This pattern requires that each input field in the group have a matching name property as the value field in the state object.
ie (reusing the same handler on mulple form inputs)
const [formState, setFormState] = useState({
name1: value1,
name2: value2,
name3: value3,
…})
const handler = e =\> { setFormState(prev =\> { {...prev, [e.target.name]:e.target.value } }) }
In the below statement, [e.target.name] is called a ___.
{[e.target.name]: e.target.value}
Computed Property
On initialization of a component, component code seems to be run twice, even though the return/render only runs once.
values generated on the first execution of component code are used in the return/render. but values from the second run are received inside the subcomponents.
this won’t matter for static initial values, but dynamically generated values should be initialized outside of the component. ie v4() or Math.random()
Tried useRef and generating values in separate function. Neither work. UseState does not preserve the first generated value either.
reminder
When updating state using an array of objects and needing to edit a single object’s values, what pattern should be used to copy the prevState for editing.
Note: this pattern is used instead of spreading the array, because the objects would be copied over by reference. AKA the arrays would be separate and unique but the objects and values inside would be tied together between the arrays.
const copyPrev = prevState.map(obj => ({…obj}))
set a gradient background going from bottom left to top right with colors red, green, then white. Place it an element good for applying the style site wide
body {
background: linear-gradient(45deg, red, green, white);
}
Can the linear-gradient css method be used with the properties background, background-color, or both?
background
The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.
reminder
const map1 = new Map();
map1. set(‘a’, 1);
map1. set(‘b’, 2);
map1. set(‘c’, 3);
What does map1.get(‘b’) return?
2
How can you take an object parameter with unknown prop-name/value pairs, and assign them to the instance of the class in one line of code?
constructor(paramObj){ //line of code }
Object.assign(this, paramObj)
Use the Map() object to create a set called letterMap that tallies a count of each character in the following string. const ABA=’abacadabagoose’
const letterMap = new Map() for (let ltr of ABA) { letterMap.set(ltr, (letterMap.get(ltr) || 0) + 1) }
You can conditionally set a function to an event property in react. This is a good way to remove or add events based on some condition.
ie Do Something
Reminder
You can pass a call back to setState() as a SECOND parameter, which will be run AFTER the new state is set.
i.e. setState({someStateProp: newStateValue}, execACallbackAfter)
OR
i.e. setState((prevSt, props) => { return newState}, execACallbackAfter)
Reminder
list the three things that can cause a component to rerender.
setState() is called.
New prop value is received.
forceUpdate is called
List the class based life cycle methods.
componentDidMount()
componentDidUpdate(prevProps, prevState)
componentWillUnmount()
For React, when setting a height relative to the body, don’t forget that there is a root element between the body and app component.
Reminder
When using flex-direction of column, the containing element should have a height. Otherwise, thier is no space between the element to allow for arranging items in the vertical direction.
Reminder
One line of code to return a random float from -45 to +45 (not inclusive).
only use Math.random() once.
Math.random() * 90 - 45
One line of code to return a random float from -30 to +50 (not inclusive).
only use Math.random() once.
Math.random() * 80 - 30
How can you make a box-shadow extend inward toward the center and behind an element, instead of radiating outward
add inset in the css value/definition.
When using gsap animations on events, I should use the play, pause, reset, reverse methods instead of recalling the initial method. This should prevent the weird behavior I get when calling the gsap animation multiple times.
Reminder. (not yet proven)
Custom Array sorting:
arr.sort((a, b) => someFunction())
if someFunction returns a value < 0 a sorts before b
if someFunction returns a value > 0 b sorts before a
if someFunction returns a value of 0 the sort stays the same.
Reminder
const arr = [0, 5, 1, 10, 99, 2, -2, 75, 6, 7, 8] sort the above array in numeric order from largest to smallest
arr.sort((a, b) => b - a)
log out the below fruit names, in order of count, descending.
const arr = [ {fruit: 'pear', cnt: 99}, { fruit: 'apple', cnt: 52 }, {fruit: 'orange', cnt: 1}, {fruit: 'Watermelon', cnt: 10}, {fruit: 'banana', cnt: 8}, {fruit: 'grape fruit', cnt: 0}, {fruit: 'peach', cnt: 2} ]
arr. sort((a, b) => b.cnt - a.cnt)
arr. forEach(f => console.log(f.fruit))
log out the below fruit names, in order of name, descending.
const arr = [ {fruit: 'pear', cnt: 99}, { fruit: 'apple', cnt: 52 }, {fruit: 'orange', cnt: 1}, {fruit: 'watermelon', cnt: 10}, {fruit: 'banana', cnt: 8}, {fruit: 'grape fruit', cnt: 0}, {fruit: 'peach', cnt: 2} ]
arr.sort((a,b) =\> { // if a normally comes before b (a **b.fruit) return -1 return 0 })
arr.forEach(f => console.log(f.fruit))**
const testObj = {prop1: ‘test’, cnt: 5}
1 Save the above object to local storage
2 Retrieve the object from local storage and assign it to a newVar as an object.
localStorage.setItem(‘testObj’, JSON.stringify(testObj))
const newVar = JSON.parse(localStorage.getItem(‘testObj’))
What are 3 initial steps to adding React Router?
- npm install react-router-dom
- import {BrowserRouter} from ‘react-router-dom’
- Wrap component with in index.js
What React Router component is used to allow only the first matching route in a list of routes to be returned.
Write a basic React Route that matches the root path only and returns a component called Home.
Write a basic React Route that would always return an About component no matter what path it’s compared to.
Use a React Router component that allow the navigation from the current path to a new path of /newpath/somewhere
What is the difference between NavLink and Link
NavLink allows you to pass a special property called activeClassName
What does the activeClassName property do for the NavLink component?
When the NavLink is clicked ALL rendered NavLinks that match it’s “to” path will dynamically receive the className specified in the property, which is useful for dynamic styling.
Note: Can use the “exact” property in the NavLink to prevent partial matches on multiple NavLink “to” paths.
Write a basic React Route that matches the root path only and returns a component called About that needs a prop of userName=”Test User Jr”.
test
What is the major reason for using the render prop instead of the component prop for passing components with props into the Route component.
example:
VS
component will cause the component to unmount and reinstantiated every time a path is matched (aka every time a a matching link is clicked), as where render will follow normal life cycle if a matching path is re-entered (aka, it may rerender by it won’t be unmounted and reinstantiated)
What are the three props that are passed into a Route’s component/render function?
history, location, match
What are the four properties found in the Router’s component/render function’s match property?
isExact, params, path, url
withRouter allows you to receive the history prop from react-router-dom, when the component is not from a Route component. You need to encapsulate the component with withRouter in it’s export statement.
Reminider
1.
Immediately redirects you to a new path. Elements after this component don’t get rendered and the route that pushed you to the Redirect is not saved to history (aka, you cant get back to it)
- props.history.push(somePath)
Adds a new path to the history and updates the URL. Allows you to back into the page/url that got you to the push statement.
3 props.history.goBack()
Will take you back to the previous route stored in history
Reminder
CSS property/value to set the background to a gradient?
going from left to right
angled 25degs to the right, off the vertical
the first 10 percent solid white
10% to 75% grade from white to red
75% to 90% grade from red to green
90% to 100% solid green
background: linear-gradient(
115deg,
white 0 10%,
red 75%,
green 90% 100%
)
React router dom v6: List 7 commonly used named components
BrouserRouter
Navigate
Link
NavLink
Routes
Route
Outlet
React-router-dom v6: List the following hooks.
Provides a function to traverse browser history (redirect URL).
Provides an object to access and update the URL query params.
Provides an object with access to param values.
useNavigate()
useSearchParams()
useParams()
ES7 React/Redux/GraphQL/React-Native snippets shortcut to insert a functional component with export using arrow functions
_rafce
ES7 React/Redux/GraphQL/React-Native snippets shortcut to insert a functional component with export and propTypes using arrow functions
_rafcp
What property do you use on a NavLink to prevent the isActive from being triggered when one of its child paths is active?
end=true OR just pass end
React Router Dom v6: In the ‘to’ property for Link, NavLink, Navigate components, you can specify an integer to direct it to jump forward or backward through browser history.
reminder
A function that takes a function as an argument, returns a function, or both?
Higher-Order function
A technique used to convert a function that takes multiple inputs to one that takes fewer (ie one or none) inputs by returning a function that takes the secondary input. You could then pass and execute the function as a callback since it will return a new function definition.
Currying
Review Code-with-mosh Redux Video #7 “Currying” for great example.
const add = (a, b, c) => a + b + c
Rewrite the above function with the Currying technique so that it can be passed into the below as a parameter.
const addMore = (addFunc, someVal) => addFunc() + someVal
The problem that you’re trying to solve is the fact that addMore does not provide any values for the add function which you’ll be passing to addMore.
const add = (a,b,c) => ( ) => a + b + c
Now running add(2,4,6) returns a new function of ( ) => 2 + 4 + 6
A function that when the same values are passed in, it will always return the same result.
ie const someFunc = (a, b) => a * b
someFunc(3, 2) will always return 6
Pure Function
Copying an object using the spread operator (ie {…someObj}) results in a shallow copy, meaning that nested objects are still copied by reference.
You can copy the nested objects by overwriting their properties with another spread operator.
ie { …someObject, someSubObj: {…someObject.someSubObj}}
OR
You could copy using JSON.parse(JSON.stringify(someObject))
OR
Use a third party library like immer
reminder
What are the three building blocks of a Redux application?
Action
Store
Reducer
A Redux Action can be thought of as an event
A Redux Store can be thought of as a giant state object
A Redux reducer can be thought of as an event handler (a PURE function that updates the store state when an event happens)
reminder
What are 4 steps to follow when building a Redux application?
Design the store
Define the actions
Create reducers
Setup the store (based on reducers)
Given a single reducer exported by default from a file ‘./reducer’, write 4 lines of code to create a Redux store using the reducer and export it by default.
import {createStore } from ‘redux’
import reducer from ‘./reducer’
const store = createStore(reducer)
export default store
The Redux store object is composed of 5 properties (all methods). With one being Symbol(observable), what are the other 4 along with the params they accept?
dispatch(action)
subscribe(listener)
getState()
replaceReducer(nextReducer)
What does the command pwd stand for?
Print working directory
What is the below array function?
Takes a function that loops though each element, returns false and exits the loop if any of the functions returns false, otherwise returns true
.every()
What is the below array function?
Takes a function that loops though each element, returns a new array with each element being the return value of each function execution.
.map()
What is the below array function?
Takes a function that loops though each element, returns a new array with each of the original elements where the executed function returned true.
.filter()
What is the below array function?
Takes a value and returns true if the value is equal (triple equal) to one of the elements in the array and otherwise returns false.
.includes()
What is the below array function?
Takes a function that loops through each element, returns the first element where the function returns true.
.find()
Order of events for an event handler with UseState
event handler starts execution
hits setVarible call
runs any setVariable fn code
schedules variable update from return value
continues to end of event handler code with original variable value
state gets updated
component code is run through
component is rendered
all useEffects that include the state variable dependency or No dependency are run in order.
Debouncing is a technique for having a timeout to wait to see if a user is completed entering data before taking an action.
useEffect, its cleanup return, with a setTimeout function is a good way to perform this technique
reminder
An example of debouncing in react.
useEffect(() => {
const identifier = setTimeout(
setFormIsValid(
enteredEmail.includes(‘@’) && enteredPassword.trim().length > 6
)
, 500)
return () => {
clearTimeout(identifier)
}
}, [enteredEmail, enteredPassword])
reminder
Write the import statement and the line of needed to Portal a render of component to a div element with the id=”overlays”
import ReactDOM from ‘react-dom’
ReactDOM.createPortal(, document.getElementById(‘overlays’))
Write a file to create/initialize/export a context object to store a list of users with addUser and removeUser actions.
import React from ‘react’
const UserContext = React.createContext({
users: [],
addUser: user => {},
removeUser: id=> {}
})
export default UserContext
Make a UserContext Provider wrapping Component file using the context from the below user-context.js file.
import React from ‘react’
const UserContext = React.createContext({
users: [],
addUser: user => {},
removeUser: id=> {}
})
export default UserContext
import UsersContext from “./users-context”
const UsersProvider = ({children}) => {
const addUserHandler = user => {}
const removeUserHandler = id => {}
const usersContext = {
users: [],
addUser: addUserHandler,
removeUser: removeUserHandler
}
return (
< UsersContext.Provider value={usersContext} >
{children}
< /UsersContext.Provider >
)
}
export default UserProvider
Every time a react component is loaded all of its children will be reloaded and all of their children, regardless of whether the props on the children were changed.
If you wrap the child’s export with React.memo() this will prevent the child from being reloaded except for when it’s props have actually changed.
Note: any reference type props (like functions) passed to the child elements would be considered as a change in props, unless you create them using useCallback.
reminder
If multiple state variables are changed in a single execution the component does NOT rerender multiple times. Instead, all of the updates are processed as a group before the component rerenders. The exception is any setVar calls during that execution that nested inside of an async function like setTimeout.
The individual setVar calls within the group can be run in any order. Thats why multiple calls to the same setVar need to use prev state AND setVar that depend on other other setVar values should be combined and updated using useReducer.
useEffect will only be called once, even if more than one of its dependencies were changed.
Key point: multiple setVar calls side by side in an execution only causes on rerender
Key point2: Multiple set calls -> all setvar are processed and updated -> One render -> One execution for each matching useEffect call
REVIEW React course with Max S -> Sec 12 (video 160 mostly) Understanding scheduling and batching
IMPORTANT NOTE In async functions any setVar calls after the first await statement gets executed individually and EACH will cause a rerender (ie batch stops after await statement). The same happens inside a setTimeout call, except an await call is not needed to separate the calls.
reminder
useMemo is the same as useCallback, exept you use it for arrays/objects instead of functions.
Common to use on stuff like sorting array, to prevent having to resort even though the array hasn’t changed.
If using on a prop, you need to call it on the parent var that’s passing the prop and when processing the prop inside the child.
reminder
API stands for?
Application Programming Interface
When passing a callback function to an event into another function, using .bind() will allow you define the ‘this’ context as well as pass in additional parameter values. the additional parameter values will be place before the internally defined parameters. https://academind.com/tutorials/function-bind-event-execution
ie
Normally you would not be able to pass the below MyFnc var to onClick, because onClick would only pass you the event var. bind allow s you to include boundVal and accept 32 into it’s definition.
const myFnc = (boundVal, event) => boundVal
onClick={myFnc.bind(null, 32)}
reminder
If you have multiple setUseStateVar executed in succession for the same variable, the prevState value in the function call version is needed to access the values returned from other calls in that execution context AND the last executed’s return value is the one that will be applied on the next render.
ie the set calls are put on the stack in order and are executed in order (still as a batch for that render cycle). If you use the var value, it will only give you the value from the last render. If you use the prevState, you’ll get the value passed from the prev set call in order(time to process the function does not interrupt the order).
reminder
What button type property does not trigger a submit on a parent form?
type = “button”
List out the 9 common folders you will use to build an express API. Plus a 10th one that will be generated with sequilize setup.
- config
- controllers
- database
- middleware
- public
- router
- socket
- uploads
- validators
- models
List the step/code to setup Sequelize for querying ms SQL.
- npm install sequelize
- npm install sequelize-cli -g (needs to be install globally since it runs from the command line as its own function)
- npm install tedious (this is the ms SQL driver.)
- create a .sequelizerc file in the root server folder with the following content
const path = require(‘path’)
module.exports = {
‘config’: path.resolve(‘./config’, ‘database.js’),
‘models-path’: path.resolve(‘models’),
‘migrations-path’: path.resolve(‘database’, ‘migrations’),
‘seeders-path’: path.resolve(‘database’, ‘seeders’)
}
- sequelize init (command to generate the above files/config)
- update/fix the generated ./config/database.js file by:
a. export the generated object (using module.exports = )
b. update the config values (ideally pulling in values from require(‘dotenv’).config() - generate db model code into ./database/migrations path
a. sequelize model:create –name [SomeTableName] –attributes [fieldName1:string, fieldName2:integer,etc…]
b. note that nothing is enclosed in quotes and don’t include brackets - update model code with defaults, unique markers, etc as needed
- sequelize db:migrate (to execute model code and generate database tables, running a second time will not update the database)
a. if you want to rerun the command and update the migration, must drop using undo: (see b.)
b. sequelize db:migration:undo - sequelize seed:create –name users (generates seeder code to help add seed data)
a. code is generated in the ./database/seeders directory
b. edit code file to insert your made up records. file contains commented code to remind how to do insert objects. The down: property will allow you to write delete code. - sequelize db:seed:all (to run insert commands created above)
a. sequelize db:seed:undo (to reverse)
Node module name used to encrypt passwords
bcrypt
Write 2 lines of code to:
- Import bcrypt into node
- Use it to save a hashed version of plainTextPwd to a variable called hashedPassword
const bcrypt = require(‘bcrypt’)
const hashedPassword = bcrypt.hashSync(plainTextPwd, 10) //10 is the number of hashing rounds
NOW( ) is used to get the current date/time in postgreSQL. What is the equivalent command in MSSQL?
GETDATE( )
Write statements with bcrypt to determine if the encryptedPwd var is equal to the submittedPwd var. Include the import statement and save the result to passwordIsValid variable.
const bcrypt = require(‘bcrypt’)
const passwordIsValid = bcrypt.compareSync(submittedPwd, encryptedPwd)
const user = {
name: ‘jordan’,
state: ‘IL’,
password: ‘mysecretpassword’
}
Write one line of code to remove the password prop completely from this user object.
delete user.password
Write a line of node code to generate a random 64 character hex coded string and save it to a var call secretKey.
const secretKey = require(‘crypto’).randomBytes(64).toString(‘hex’)
Write code for node, including the import statement to generate a token from a ‘user’ object, with the encryption key = someKey, and expires after a week. Save it to a var called token.
const jwt = require(‘jsonwebtoken’)
token = jwt(user, someKey, {expires: 60 * 60 * 24 * 7} //expires is in seconds for integer and ms for string number.
What is a good validation package I could use in my node API code ?
express-validator
What are 9 npm packages I should install by default in my node api’s
express
express-validator
bcrypt
dotenv
jsonwebtoken
sequelize + tedious and/or mssql
helmet
cors
nodemon –save-dev
Write out 8 variables likely used in .env file for api (use lower case for easier typing here, but use upper case in app)
app_key
app_url
app_port
db_server
db_user
db_password
db_name
db_port
write 1 line of code that makes process.env object available with .env file values.
require(‘dotenv’).config( )
1 What are the 4 property names that you should export from .sequelizerc as part of an object that describes the folder/file path for each property.
- what function are you going to use to generate the values for each config
config
models-path
migrations-path
seeders-path
path.resolve(‘folderPath’, [filename])
list out the main properties dbConn.js should export
hint) {prop1, prop2, prop3, prop4, prop5: {subProp}}
user
password
database
server
options.trustServerCertificate
What property name and value do you need to add to fields in a sequelize migration template for MS SQL to:
- ) apply the current time.
- ) specify that the field should be unique
defaultValue: sequeslize.literal(‘GETDATE( )’)
unique: true
List all sequalize-cli commands
sequelize db:migrate Run pending migrations
sequelize db:migrate:schema:timestamps:add Update migration table to have timestamps
sequelize db:migrate:status List the status of all migrations
sequelize db:migrate:undo Reverts a migration
sequelize db:migrate:undo:all Revert all migrations ran
sequelize db:seed Run specified seeder
sequelize db:seed:undo Deletes data from the database
sequelize db:seed:all Run every seeder
sequelize db:seed:undo:all Deletes data from the database
sequelize db:create Create database specified by configuration
sequelize db:drop Drop database specified by configuration
sequelize init Initializes project
sequelize init:config Initializes configuration
sequelize init:migrations Initializes migrations
sequelize init:models Initializes models
sequelize init:seeders Initializes seeders
sequelize migration:generate Generates a new migration file
sequelize migration:create Generates a new migration file
sequelize model:generate Generates a model and its migration
sequelize model:create Generates a model and its migration
sequelize seed:generate Generates a new seed file
sequelize seed:create Generates a new seed file
What does ORM stand for, in relation to databases?
Object Relational Mapping
What is the additional install package name and corresponding dialect property value needed with sequelize for each of the following databases?
1 Postgres
2 MySQL
3 MariaDB
4 SQLite
5 Microsoft SQL Server
package name / dialect string value
1 pg pg-hstore / postgres
2 mysql2 / mysql
3 mariadb / mariadb
4 sqlite3 / sqlite
5 tedious / mssql
findById() is Sequalize was replaced by what after version 5
findByPk
What does OWASP stand for?
Open Web Application Security Project
What are the top ten web app security risks identified by OWASP?
2021 compaired to 2017 https://owasp.org/www-project-top-ten/
A01:2021-Broken Access Control moves up from the fifth position; 94% of applications were tested for some form of broken access control. The 34 Common Weakness Enumerations (CWEs) mapped to Broken Access Control had more occurrences in applications than any other category.
A02:2021-Cryptographic Failures shifts up one position to #2, previously known as Sensitive Data Exposure, which was broad symptom rather than a root cause. The renewed focus here is on failures related to cryptography which often leads to sensitive data exposure or system compromise.
A03:2021-Injection slides down to the third position. 94% of the applications were tested for some form of injection, and the 33 CWEs mapped into this category have the second most occurrences in applications. Cross-site Scripting is now part of this category in this edition.
A04:2021-Insecure Design is a new category for 2021, with a focus on risks related to design flaws. If we genuinely want to “move left” as an industry, it calls for more use of threat modeling, secure design patterns and principles, and reference architectures.
A05:2021-Security Misconfiguration moves up from #6 in the previous edition; 90% of applications were tested for some form of misconfiguration. With more shifts into highly configurable software, it’s not surprising to see this category move up. The former category for XML External Entities (XXE) is now part of this category.
A06:2021-Vulnerable and Outdated Components was previously titled Using Components with Known Vulnerabilities and is #2 in the Top 10 community survey, but also had enough data to make the Top 10 via data analysis. This category moves up from #9 in 2017 and is a known issue that we struggle to test and assess risk. It is the only category not to have any Common Vulnerability and Exposures (CVEs) mapped to the included CWEs, so a default exploit and impact weights of 5.0 are factored into their scores.
A07:2021-Identification and Authentication Failures was previously Broken Authentication and is sliding down from the second position, and now includes CWEs that are more related to identification failures. This category is still an integral part of the Top 10, but the increased availability of standardized frameworks seems to be helping.
A08:2021-Software and Data Integrity Failures is a new category for 2021, focusing on making assumptions related to software updates, critical data, and CI/CD pipelines without verifying integrity. One of the highest weighted impacts from Common Vulnerability and Exposures/Common Vulnerability Scoring System (CVE/CVSS) data mapped to the 10 CWEs in this category. Insecure Deserialization from 2017 is now a part of this larger category.
A09:2021-Security Logging and Monitoring Failures was previously Insufficient Logging & Monitoring and is added from the industry survey (#3), moving up from #10 previously. This category is expanded to include more types of failures, is challenging to test for, and isn’t well represented in the CVE/CVSS data. However, failures in this category can directly impact visibility, incident alerting, and forensics.
A10:2021-Server-Side Request Forgery is added from the Top 10 community survey (#1). The data shows a relatively low incidence rate with above average testing coverage, along with above-average ratings for Exploit and Impact potential. This category represents the scenario where the security community members are telling us this is important, even though it’s not illustrated in the data at this time.
What does TDD stand for?
Test Driven Development
What are the development phases of TDD
Red, Green, Refactor
What is the Red phase of TDD?
Write a test for the expected behavior
What is the green phase of TDD
Write the code for the red test (expected behavior test) to pass
What is the Refactor phase of TDD
Clean up your code (remove code duplication and etc)
Jest naming convention is that its root folder be “__test__” and files have an extension of .spec.js or .test.js and are in pascal case (ie UserReg.spec.js)
reminder
What is the shortcut key to rename a highlighted file in vscode
F2
What is the shortcut key to autoformat current file in vscode
Shift + Alt + F
What is the shortcut key to switch over to the Explerer window in vscode
ctrl + shft + e
How do you search for or edit shortcut keys in vscode and which are some that I should edit on a new system.
Ctrl + shft + p
search for “Preferences: open keyboard shortcuts”
Should update explorer.newFile to ctrl + n
should update explorer.newFolder to ctrl + shft + n
workbench. action.files.save to ctrl + s
workbench. action.files.saveAll to ctrl + shft + s
What are 7 datatypes in Sequelize along with their corresponding datatypes in MySQL?
Sequelize dt / MySQL dt
STRING / VARCHAR(255)
TEXT / TEXT
BOOLEAN / TINYINT(1)
INTEGER / INTEGER
FLOAT / FLOAT
STRING(2000) / VARCHAR(2000)
DATE / DATE
What are the 5 properties you can use to configure your model’s table (the third parameter in the define( ) function) along with the value type that they accept
timestamps / boolean
freezeTableName / boolean
tableName / string
version / boolean
paramoid / boolean
For the .sync() function in Sequelize, what are two alternate objects you can pass to change the way it syncs
.sync({force: true})
.sync({alter: true})
Describe the 3 properties you can pass .define() when creating a model, in order.
table name as a string
an object modeling out the field values for that table
options for creating our table
How would you add your own auto incrementing - primary key user_id field to the modeling parameter when configuring the definition of a Sequelize model
{
user_id: {
type: Sequelize.dataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
}
}
You have two models (User and Product) defined for a sequelize instance (called sequelizeApp1).
A.) How would you call the sync methed to build just the User table?
B.) How would you sync all tables?
A.) User.sync( )
B.) sequelizeApp1.sync( )
What is the property and value to prevent nulls in a sequelize model definition?
allowNull: false
Sequelize note:
You can use: .build( ) together with .save( ) to create a saveable object separately before saving it to the database. You might do this is you need to run some additional changes/executions to the object before saving it to the database.
OR
You can use: .create( ) which does the build and save operations all at once.
reminder
List out 6 common sequalize data action methods (not query methods) and what they do
.create( ) - builds, saves to db, and returns a data object
.build( ) - builds and returns a data object, does not save to db
.save( ) - saves/updates a data object to the database (after build/create)
.reload( ) - reverts the data object back to its origonal build/create state
.destroy( ) - deletes the data object (undos save operation)
.bulkCreate([]) - builds, saves to db, and returns an array of data objects
write sequelize queries to return the following given a User model and ‘sequelize’ db instance.
1) select * from users – returning a sequelize data array
2) select username, password from users – returning a sequelize data array
3) select username as ‘login_id’, password from users – returning a sequelize data array
4) select SUM(age) as ‘how old’ from users – NOTE: using an ‘as alias’ is required so that sequelize can return an object property name for the sum of the age. it does not default ‘age’
5) select * from users – excluding the password and age field
6) select * from users where age = 45
7) select username, password from users where age=45
8) select top 2 * from users
9) select * from users order by username DESC, age ASC
10) select username, SUM(age) as ‘sum_age’ from users group by username
11) select * from users where age=25 or username=’pizza’
12) select * from users where age > 25
13) select * from users where char_length(username) = 5
14) select * from users – RETURN result as POJO
User.findAll()
User.findAll({ attributes: [‘username’, ‘password’])
User.findAll({attributes: [[‘username’, ‘user_id’], ‘password’]
User.findAll({attributes: [[sequelize.fn(‘SUM’, sequelize.col(‘age), ‘how old’)]]
User.findAll({attributes: {exclude: [‘password’, ‘age’]}})
User.findAll({where: {age:45}})
User.findAll({attributes: [‘username’, ‘password’], where: {age:45})
User.findAll({limit: 2})
9) User.findAll({ order: [[‘username’, ‘DESC’], [‘age’, ‘ASC’] ]
10) User.findAll({
attributes: [‘username’, [sequelize.fn(‘SUM’, sequelize.col(‘age’)), ‘sum_age’] ],
group: ‘username’
})
11) User.findAll({ where: { [Sequelize.Op.or]: { age: 25, username: ‘pizza’ } } })
12) User.findAll({ where: { age: { [Sequelize.Op.gt]:25 } } })
13) User.findAll({
where: sequelize.where(
sequelize. fn(‘char_length’, sequelize.col(‘username’)),
5
)
}
14) User.findAll({ raw: true })
Sequelelize: Updating Where (User model, users table, sequelize db instance, Sequelize class)
1) update users set username=’tom’ where age=45
1) User.update({ username: ‘tom’}, {where: {age: 45}})
Sequelelize: Delete Where (User model, users table, sequelize db instance, Sequelize class)
1) delete from users where username=’pizza’ – returns number of deleted in array container
2) delete from users – delete all users, not the table
1) User.destroy({where: {username: ‘pizza’}})
2) User.destroy( {truncate: true})
Sequelelize: select utility methods (User model, users table, sequelize db instance, Sequelize class)
select MAX(age) from users
select SUM(age) from users
select SUM(age) from users where username=’tom’
User.max(‘age’)
User.sum(‘age’)
User.sum(‘age’, {where: {username: ‘tom’}})
If you want to await a group of asynchronous functions to complete before proceeding execution, what tool can you use.
ie.
step 1 await single function
step 2 await a single execution
step 3 await for the completion of multiple functions BUT allow them to run asynchronously (in any order at same time)
step 4 continue execution
Promise.all( […eachAsyncFunc( )] )
What does IIFE stand for?
Immediately invoked function expression
List other Sequelize query methods other than .findAll()
Hints:
1) returns a result base on Primary Key
2) returns the first row it finds that matches it’s conditions. If now conditions given it will just return the first row in the table.
3) queries and returns a record and if not found, it will generate and insert the record
4) return results same as findAll plus it gives a count of records returned
1) .findByPk( )
2) .findOne( )
3) .findOrCreate( )
4) .findAndCountAll()
An object key defined with square brackets is called a ___
ie { [nameVar]: someValue }
Computed property
What are the commands to generate a GUID/UUID value for mssql, MySQL, postgres, and sqlite respectively? Note, that it seems that you can use all of these as default generators, except in sqlite, which appears to only accept static defaults.
mssql / newid( )
postgres / gen_random_uuid()
mysql / uuid( )
sqlite / hex(randomblob(16))
Code to get the current dialect value when marking up the up( ) function in sequelize migrations.
queryInterface.sequelize.options.dialect
You can use the following vscode settings to enable emmet for all js files. However it’s better not to add it and name react components with .jsx, as emmet is on by default for that extension. Also, when emmet is on in .js files that are not react components, it dirties up code completion.
“emmet.includeLanguages”: {
“javascript”: “javascriptreact”
},
reminder
What are the two common obj.method( )’s that you will use for the up/down methods in your seeder file?
queryInterface.bulkInsert() for up
queryInterface.bulkDelete() for down
What are the two common obj.method( )’s that you will use for the up/down methods in your migrations file?
queryInterface.createTable( ) for up
queryInterface.dropTable( ) for down
Show math to convert 0b101101 to decimal
45
(25 * 1) + (24 * 0) + (23 * 1) + (22 * 1) + (21 * 0) + (20 * 1)
32 + 0 + 8 + 4 + 0 + 1 = 45
Show math to convert 0xAB9 to decimal
2745
(162 * 10) + (161 * 11) + (160 * 9)
(256 * 10) + (16 * 11) + (1 * 9)
2560 + 176 + 9 = 2745
With sequelize class modeling pattern using the autogenerated index
Class pattern with generated index file:
index will automatically associate the db connection/instance from config
index will use the modelName property for the defined export name. ie modelName.findOne( )
index does not care about the file name nor the classname, so you can name them whatever you want.
index provides named exports of { sequelize, Sequelize, eachOfYourModelNames}
you must specify timestamps: false if your table/migration does not use updatedAt & createdAt, even if your model does not have them listed in fields (otherwise queries will try to select them)
If not using an ‘id’ column you must add modelClassName.removeAttribute(‘id’) after the init call (before the return call) to remove this default field and to keep it from generating in queries. Also, some queries like findOne will still use ‘id’ to generate Order by clauses. This can be fixed by specifying an order: value. Alternativly, specifying an alternate PK field will correct the whole issue for this model.
the call to findOne() or any other queries will automatically query the tableName = modelName pluralized. You can add a tableName property to the model and specify whatever table name you want the model to query against.
reminder
using Sequelizes’ .define( ) method to generate model against autogenerated index.js
This will work the same as with the generated Model class pattern, just need to export a (sequelize, DataTypes) => { //some code }function that returns the object from executing sequelize.define( ).
The modelName that is exported by name from index.js comes from the first parameter passed to define.
The tableName will be autogenerated from the modelName (pluralized by default unless you pass the freezeTableName: true option). You can pass a tableName: ‘someName’ option to use a completely different tableName.
pass timestamps: false option to stop queries from assuming table has createdAt, updatedAt fields
if the table does not have an ‘id’ field, you need to define an alternate primaryKey fields OR call removeAttribute on the returned sequelize.define( ) variable before returning from the exported function
index.js does not care what the filename or return variable name is.
reminder
Sequelize assumes your tables will have ‘id’, ‘createdAt’, ‘updatedAt’ fields. If you don’t:
Sequelize injects an ‘id’ field into all models by default. You can define an alternate PK field and this default will be overwritten.
If you don’t have an alternate PK field and no ‘id’ field, you must use modelName.removeAttribute(‘id’) before using query functions with it. Also, any automatically ordered queries will default with ‘id’, so you’ll need to overwrite with an order: ‘something’ option.
Also, the timestamp option needs to be set to false if you don’t have timestamp fields in your table.
reminder
the autogenerated models/index.js file, when imported, will:
loop through each model file and execute the returned function passing in a dbInstance generated by config. It will return the models created as properties, including a Sequelize property and sequelize property (ie dbInstance)
If I import the models/index.js file for its functionality, every model file must have the module.exports signature of (sequelize, DataTypes) => modelObj (modelObj can be created with .define( ) or the Model class). Any other type of exports will cause index.js’ code to fail.
I can separately import these specially exported modules and just pass them my own dbInstance to override the sequelize dbInstance generated by modules/index.js
reminder
How do I include a partial scss or CSS file into my current one? ie a _variables.scss in a ../assest/scss folder
@import ‘../assets/scss’
I have the below _variables.scss file in ‘../assets/scss’. What do I add to the file to export the variable for use in a jsx file. Once exported, how do I import it and set a variable equal to one of the values in Javascript?
$bg-color: ‘gray’;
$bg-main: ‘blue’;
add to variable.scss for export:
:export {
bgColor: $bg-color;
bgMain: $bg-main;
}
to import:
import variables from ‘../assets/scss/_variables.scss’
to use:
const { bgMain } = variables //used destructuring here but can use regular assigning also.
What are the 4 css property names to set each of the individual border radiouses?
- border-top-left-radius
- border-top-right-radius
- border-bottom-left-radius
- border-bottom-right-radius
Write code that exports a configured axios object that connects to API at HTTP://localhost:3001 and tell it to use JSON. Don’t forget the import and export code.
import axios from ‘axios’
export default axios.create({
baseURL: ‘http://localhost:3001’,
headers: {
Accept: ‘application/json’
}
})
What does the Optional Chaining operator (ie ?. ) do?
It can be placed before any property on an object, array index call ( ie [] ), or function execution (ie ( ) ) to escape throwing an error if the object/array/func is undefined. Instead it will return undefined.
someObj?.someProp
What is the ?. operator, attached to this object, called?
Optional Chaining operator
With Sequelize queries on Models that contain getters, any call for raw:true will not execute the getter. In order for the getter values to be process, you must be pulling the value from a sequelized object. So, you need to use .toJSON() or call the property directly on the sequelized object, to get the calculated value. ie seqReturnObj.toJSON() or seqReturnObj.someCalculatedProperty.
reminder
Helmet can overwrite CORS policy, and has blocked img src=http…somefile.svg elements for some reason. You can use helmet and disable its cors policies by calling it as:
app. use(helmet({crossOriginResourcePolicy: {policy:’cross-origin’}}))
https: //helmetjs.github.io/
reminder
Sequelize provides constraint properties and validator properties.
Constraint properties apply on db sync or migration only and are only obeyed as a result of database errors. IE javascript will not stop the execution of the sql query.
Validation properties are checked before javascript sends a sql query to the database.
stuff like unique and all properties inside of validator are Validation properties.
stuff like primaryKey, autoIncrement are constraint properties.
things like allowNull and defaultValue can be either
reminder
Terminal Shortcuts
- Close current focused tab while in command prompt — custom
- Terminal: Kill the Active Terminal Instance, When: terminalFocus
- add a tab
- go up/left one tab while in command prompt
- go down/right one tab while in command prompt
- move focus to tab list
- remove selected tab while in tab list
- rename selected tab while in tab list
- move back to command prompt while in tab list
- scroll up / down
- ctrl + shft + F4
- ctrl + shft + `
- ctrl + PgUp
- ctrl + PgDown
- ctrl + shft + \
- Del
- F2
- Enter (on selected tab)
- crtl + shft + PgUp / PgDown
With the following axios call in a try catch block. 1) How do you access the data if the call is successful and 2) how do you get the returned API’s error data (not the HTTP error)?
try {
const result = await axios.get(url, { email, password })
console.log( ___ ) // 1. access returned data ie fill in the blank
} catch (err) {
console.log( ___ ) // 2. access error data sent from api server, not the HTTP error
}
- result.data
- err.response.data
Set the bearer/token on this axiosObj variable using the value stored in token.
axiosObj.defaults.headers[‘Authorization’] = Bearer ${token}
What should the client side service functions do (in reference to auth, for now)
Make call with the axios api objects, receiving and passing in needed params.
The service will return the desired result data from the axiosObj calls or throw the error received
If successful user authentication, the service will apply an Authorization token to the axios API object
ie
- try
- const result = await axiosObj.post(somthing)
- axiosObj.defaults.headers[‘Authorization’] =
Bearer ${token}
- return result.data
- catch(error)
- throw error
In a controller, how do you get the Bearer token?
req.headers[‘authorization’] //authorization must be lower case
What are the 4 config properties for configuring a Multer uploader middleware? IE multer({prop1, prop2, prop3, prop4})
storage or dest
fileFilter
limits
preservePath
What method on the multer object do you use to create a storage config object? What 2 properties does this config object require?
.diskStorage( { } )
destination
filename
What are the properties of a file returned by multer?
- fieldname
- origionalname
- encoding
- mimetype
- size
- destination - files stored in DiskStorage
- filename - files stored in DiskStorage
- path - files stored in DiskStorage
- buffer - files stored in MemoryStorage
When passing a fileFilter function to multer, the function receives req, file, and cb. Within the function, you execute cb(null, false) to reject the file, cb(null, true) to accept the file, and cb(new Error(‘Some error message’)) to throw an error.
reminder
With file uploads, you can add a third argument (as an object) to the axios call that has an onUploadProgress property that takes a callback function to be run on change of upload progress. The callback passes a progressEven argument that is an object that contains the uploaded and total values.
reminder
to use the onUploadProgress event from an imported axios service to update state values, you need to define the call back function or the whole options objected inside your compont (setting your state in the callback’s definition) and pass your definition to the axios service function.
reminder.
What are the install package names for socket.io on the 1.) client and on the 2.) server
- socket.io-client
- socket.io
What are the two packages that need to be installed for internationalization in a React project?
i18next react-i18next
Write out the basic template to configure and initialize i18n for react to be able to translate ‘hello world’ and water between english ( en ) and Spanish (es). Including imports.
- import i18n from ‘i18next’
- import { initReactI18next } from ‘react-i18next’ // note the capital I
- i18n
- .use( initReactI18next )
- .init({
- resources: {
- en: {
- translation: {
- “helloWorld”: “hello world”, //notice use of JSON for word list, not POJO
- “water”: “water”
- }
- },
- es: {
- translation: {
- “helloWorld”: “hola world”, //notice use of JSON, not POJO
- “water”: “agua”
- }
- }
- },
- lng: ‘es’,
- fallbackLng: ‘en’,
- interpolation: {
- escapeValue: false
- }
- })
You don’t make an export statement from a plain .json file. You can simply import from the file into a variable with any name. No need to parse either.
ie import anyName from ‘./someFile.json’
reminder
List all the property names used in the i18next init method. tab in (3spaces) sub properties
- resources
- (languageAbbreviation)
- translation
- (wordLabelForTranslation)
- lng
- fallbackLng
- interpolation
- escapeValue
You can create a file for the purpose of executing a function (imported, IFEE, defined). You would would write or inport the function and execute it in the file. You would not export the function from the file. Just importing the file into your app would trigger the execution.
ie import ‘./someFileWithExecutedFunc’
reminder
How do you access your translations or change language? Write the import and lines of code to do both.
- import { useTranslations } from ‘react-i18next’
- const { t, i18n } = useTranslations( )
- const textExample = t( ‘translatedTextKey’ )
- i18n.changeLanguage( ‘languageKey’ )
When adding your own primary key in a sequelize model, you must define it with primaryKey and a an autoIncrement or defaultValue of DataType.UUIDV4
If no id at all then Model.removeAttribute(‘id’)
If you use ‘id’ you can omit it from model unless, you need to default a UUID
KEY POINTS: ‘id’ integer primary key is defaulted into the model and is the only field that is auto excluded from inserts
ANY TIME you want the database to generate the default for an insert, you must use exclude the attribute
reminder
app.use(helmet({crossOriginResourcePolicy: {policy:’cross-origin’}}))
Reminder
REMINDER. Don’t try to set the value on a input of type file.
You might get the following errors:
The above error occurred in the ( input ) component:
Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
reminder
To set the initial value for a select tag on render in React, you must use the _???_ attribute. Most other methods will thrown an error.
defaultValue
When doing a model.update() you must add returning: true if you want the updated record back (will get [count, resultsArray] instead of (counts) )
You must add individualHooks: true if you want the hooks to be processed.
reminder
a model hook signature = (instance, options) => { }
The instance param starts out with all it’s current dataValues set with the new values passed into the methed called on the model (ie model.update(newObject,{ where: … } ) ). The values ommited from the passed in object get set to the values currently in the database.
the instance object also stores the previous values, those start out as the values pulled from the database.
the changed method will return true if you passed in a different value from what’s in the database. Done by comparing prevDataValues to current dataValues.
If you change a value inside the hook it would shift the current and previous dataValues with your new value.
reminder
- Use the multiple attribute to allow multiple files
- Use the accept attribute to limit file types (comma separated string of extensions or mime types, including something like image/*)
- Whether single or multiple files, the files get stored/added to a FileList object which is read only.
- The FileList is stored in inputEl.files. It’s not an array, but can be spread into an array.
- To clear an input, you can set inputEl.value = ‘’ (empty string)
- DataTransfer class allows you to create an alternative to a fileList, but with the ability to add File objects ( using dataTransfer.items.add(file) )
- You can add a dataTransfer file list (overwrite an inputs files) with inputEl.files = dataTransfer.files
- DataTransfer was created for drag and drop but seems to work on simple input file types.
- You can also set inputEl._value (note the underscore) with a regular array of File objects, but it does not update the file count when viewing the original input box.
- You cant control a file input. You must use references to update the value.
- https://pqina.nl/blog/the-trouble-with-editing-and-uploading-files-in-the-browser/ form some good info.
reminder
when chaining errors by rethrowing them, each the receiving function must be an async function or use .catch or be a promise.
Particularly with receiving functions that use try catch block, you must await the statements that the error could be thrown too in the try block.
Otherwize you may get an uncaught error from the function rethrowing the error.
reminder
an error/json caught from axios is stored in error.response.data
reminder
When using multiple animated items in one container that leave or reset within the container, you should position: absolute the items, as when they leave, reset or move to the edges of the container, they will cause the container to change causing a jitter or jumping effect on the other items.
reminder
Whenever you start a new line with something enclosed in parenthesis, you must close/end the previous line of code with a semicolun to prevent javascript from thinking its executing a function.
reminder
You can play audito by using the new Audio(‘path/fileName’) and calling play( ) on the object created
const sound = new Audio(‘path/someFile’)
sound.play( )
You can also import the sound file and pass the imported variable into the new method. Also, you call play on new Audio using it like an IFEE
reminder
you can call scrollIntoView(true) on an element to force a scroll to that element (ie it’s a to anchor method)
someElRef.current.scrollIntoView(true)
reminder
Socket.io cors error from the client.
When creating the io object on the server, using socketIo(server, config), you must pass an object to the config param that contains a cors property and set the origin property.
otherwise you could trigger a cors error
example
- const socketIo = require(‘socket.io’)
- const SocketServer = (server) => {
- const io = socketIo(server, {
- cors: {
- origin: “*“
- }
- })
- io.on(‘connection’, (socket) => {
- socket.on(‘join’, async (user) => {
- console.log(“New user joined: “, user.firstName)
- })
- })
- }
reminder
If getting an error from my reducers about not being able to convert non-serializable data, you can ignore the error and configure the store to not show the error by adding the below middleware property
will look up later on best practice for this issue.
- export default configureStore({
- reducer: {
- lang: langSlice.reducer,
- auth: authSlice.reducer,
- chat: chatSlice.reducer
- },
- middleware: (getDefaultMiddleware) => getDefaultMiddleware({
- serializableCheck: false,
- })
- })
reminder
what is the heroku command to list all env variables including built in ones, on a deployed app (ie chat-server app)? (assume you already logged into the cli using heroku login)
heroku run printenv -a chat-server
If you attempt to deploy an app to a server that self builds, it will fail if you only installed your font awesome pro license/token to the local/global config. What are the steps to allow the hosting service to build with your pro token.
- create a .npmrc file in the project root
- Add @fortawesome:registry=https://npm.fontawesome.com/ to the file
- Add //npm.fontawesome.com/:_authToken=${FONTAWESOME_NPM_AUTH_TOKEN} to the file
- Add the actual token to an env var called FONTAWESOME_NPM_AUTH_TOKEN on the host service
Alternatively you could skip adding the environment var and replace ${ envVarKey } with the actual token on step 3
What are the 4 pillars of OOP
Encapsulation
Abstraction
Inheritance
Polymorphism
command line to generate a console based c# project
dotnet new console
command line to start a c# console project
dotnet run
What are the implicit (implied) using statements in .net 6.0
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
Command to print a list of all the C# project templates.
dotnet new
List the primative datatypes in C#
- byte
- short
- int
- long
- float
- double
- decimal
- char
- bool
What is the byte size and range of values for the following primatives?
- byte
- short
- int
- long
- float
- double
- decimal
- char
- bool
- 1B / 0-255
- 2B / -32768 to 32767
- 4B / +- 2.1billion
- 8B / +- 9.2 * 10^18
- 4B / ±1.5 x 10^-45 to ±3.4 x 10^38
- 8B / ±5.0 × 10^-324 to ±1.7 × 10^308
- 16B / ±1.0 x 10^-28 to ±7.9228 x 10^28
- 2B / Unicode char set
- 1B / True or False
How do you write the assigment of a decimil or float value in C#?
use the value 1.25 as an example and someVar as the variable name
float someVar = 1.25f;
float someVar = 1.25m;
What are 4 common non-primative types in C#?
- String
- Array
- Enum
- Class
When deploying a React router app to a web server/service (particularly Netlify) you need to add a ___ file to the public directory with what command? Note: the purpose of this file is to transfer routing over to the route of your app on initial load. It fixes the page not found error when someone loads/refreshes the site from a route.
https://www.freecodecamp.org/news/how-to-deploy-react-router-based-app-to-netlify/
_redirects
/* /index.html 200
File uploads to Heroku, through the application, will work, but are only temporary. Uploaded files will be lost when the Heroku dyno restarts (at least daily).
reminder
process. stdin.on(“data”, (input)=> {callback function})
process. stdin.on starts a listener process on the command line
the process can be programatically stopped with process.exit()
entered input gets suffixed with \r\n
reminder
Easiest way to pad leading characters on a string.
return someNumberString as a string with 5 digits, using leading zeros.
return someNumberString.padStart(5, ‘0’)
convert someNum to a 32 bit binary string
someNum.toString(2)
convert a 32bit binary string call someBinString to a decimal number
parseInt(someBinString, 2)
What does IAM stand for in regard to Amazon Web Services?
Identity Access Management
What does S3 stand for in Amazon S3
Simple Storage Service
What are the properties needed to configure an AWS S3 object? Insure correct casing.
resource on S3 aws-sdk - https://stackabuse.com/uploading-files-to-aws-s3-with-node-js/
accessKeyId, secretAccessKey, region, signatureVersion
Write the call on s3 needed to get a file upload URL. Insure correct case sensitivity.
- s3.getSignedUrl(
- ‘putObject’,
- {
- Bucket: ‘bucket-name’,
- ContentType: ‘image/*’,
- Key: ‘thePath/AndFileName.ext’,
- Expires: someIntSeconds
- },
- (err, url) => {
- //some code to use the url or err
- }
- )
what is the aws s3 url called that can be generated programmatically to allow a non user or application to temporarily add or retrieve a file from your s3 bucket?
presigned URL
Generate and configure an S3 object 3 ways. 1. From the default export of ‘aws-sdk’ ,passing configs to that Class. 2. Pull the default export of aws-sdk and configure the s3 object while creating it. 3. use the named import of S3.
just use a presaved config var called awsConfigs to pass in the configs for this problem.
- const AWS = require(‘aws-sdk’)
- AWS.config.update(awsConfigs)
- const s3 = new AWS.S3()
- const AWS = require(‘aws-sdk’)
- const s3 = new AWS.S3(awsConfigs)
- const S3 = require(‘aws-sdk/clients/s3’) or const {S3} = require(‘aws-sdk’)
- const s3 = new S3(awsConfigs)
Where do the validation methods for express validator come from?
validator. js
https: //www.npmjs.com/package/validator
What are the 12 validation methods in express-validator that are additional to those included from validator.js
- .bail()
- .custom()
- .exists()
- .if()
- .isArray()
- .isObject()
- .isString()
- .not()
- .notEmpty()
- .optional()
- .run()
- .withMessage()
To keep from getting an Uncontrolled changed to Controlled component error, you must make sure the initial value from your variable is not returning undefined.
reminder
write a comparison to determin if a property exists in an object.
use the below example
const fruits = {
apple: ‘5 in inventory’,
orange: ‘2 in inventory’,
cherries: ‘0 in inventory’
}
determin if this this object has a banana property
(‘banana’ in fruits)
//should return false
‘this’ inside of an arrow function represents the ‘this’ value of the containing function for which it was defined in.
strict mode forces the value of the unbound ‘this’ variable to be ‘undefined’ instead of being added to the window object.
inside class constructors ‘this’ follows strict mode rules.
reminder
what are the 5 parameters profided in each file(aka module)
module, exports, require, __filename, __dirname
the dog weighs ${someNum} lbs
What kind/type of string does the above expression use
Template String
You have to rewatch Mosh H Node.js Extending Event Emmiter lecture, currently Section 2 Vid#21
Great example of creating your own class that extends a Node class and is used in other files.
reminder
Show the equivilant x upgradability for the following npm version markers. x representing the part of the version that can be upgraded.
^4.2.5
~4.2.5
4.2.5
- x //upgrade patches or minor version
- 2.x //upgrade with patches
- 2.5 //keep same version
command to list out all node module versions in a tree?
command to list only node module versions that your app depends on?
npm list
npm list –depth=0
command to see the package.json file for a node module?
npm view someNodeModuleName
command to see just a node modules’s dependencies?
command to see all versions of a node module?
npm view moduleName dependencies
npm view moduleName versions
How to install a specific version of a node module?
ie version 2.4.2 of mongoose
npm install mongoose@2.4.2
command to list out any dependencies that have newer versions available?
command to list out any global packages that have newer versions available?
npm outdated
npm -g outdated
command to trigger ALL node modules to update to the latest versions (minor and patch) based on their version prefixes (^ or ~)
trigger update for ALL global packages
Note: to upgrade a major version on ALL outdated node packages, you need something like npm-check-updates module.
Note: you should be able to upgrade the major version on a single package by running the install command again.
npm update
npm -g update
step/commands to add my own package to npm?
note: rewatch Mosh H Section 3 videos 38 and 39 Publishing a package and Updating a published package for review and more detail.
cd into the project folder
npm login (npm adduser if wanting to create an account via command line)
npm publish (project must have a unique name)
What does REST stand for?
Representational State Transfer
How can you set environment variables on Mac and on Windows? set PORT to 5000 as an expample.
for mac: export PORT=5000
for win: set PORT=5000
given the route ‘http://somesite.com/api/:id/:classOf?hasDogs=yes?isGraduated=no’ what request object holds the id and classOf and what request object holds hasDogs and isGraduated.
req. params
req. query
what does status 400 mean
Bad Request
What does status 404 mean?
Resource not found
how to designate a static folder in node.js
use the public folder which is nested in src from the root
a test file can be read using the following get call: http://localhost:3000/pubfiles/test.txt
Note/Reminder: the static method is always relative to the root of the app no matter where the call is made from.
app.use(‘/pubfiles’, express.static(‘src/public’))
Express has a list of middleware that can be used with it.
You can find the list on Express’ website under Resources/Middleware
can view at https://expressjs.com/en/resources/middleware.html
reminder
Setting env vars:
in bash shell you can call:
export to list all env vars
echo $SOME_VAR to print specific env variable
You can set env vars with: export SOME_VAR=”value” OR SOME_VAR=value (no command)
in Powershell use: $env:SOME_VAR=”production”
*IMPORTANT: These values will NOT persist across terminal sessions. It will only apply to the apps/server sessions running in that terminal window.
Best options for persistence or repeat use
script the var with a call to app: USER_ID=239482 USER_KEY=foobar node app.js
OR use a .env but without having to call dotenv in my code
create a .env file for the app
install dotenv
call a dotenv command line before running the app: node -r dotenv/config index.js
reminder
creating application variables/config based on environment and are not highly secure(not passwords and such)
- npm install config
- create a folder called config in the root
- create JSON files with names that matches exactly to the NODE_ENV name that you have custom configs for.
- import config into any files where you need to pull values
- call config.get(‘property.anySubProperty.etc’)
Note there is an option to create a file called custom-environment-variables.json in this folder which allows you to map the environment variables to config.get() properties just using the environment variable name as the property value. no need to use process.env.VAR_NAME
The above is an easy way to read env variable. BUT it does not set env vars. You still set those using dotenv, command line, or hosted settings.
reminder
module for debugging - cleaner alternative to console logging
- install debug
- const debugMode1 = require(‘debug’)(‘app:mode1’)
- const debugMode2 = require(‘debug’)(‘app:mode2’)
- const someOtherDebugger = require(‘debug’)(‘other:debugSomething’)
- wherever I want to console log something related to a debug use:
- debugMode1(‘Print some message/log related to debug Mode1’)
- set a DEBUG environment variable with the instance of debug you want to run:
- i.e. DEBUG=app:mode1
- start the app like normal with the new environment variable OR set the env variable with the startup command.
Note you can run multiple debug instances with DEBUG=app:mode1,app:mode2,etc OR DEBUG=app:*
reminder
How would you incorporate the pug templating engine
change the default root views folder to src/views
and
return a pug template as HTML response on the /test route
- app.set(‘view engine’, ‘pug’)
- app.set(‘views’, ‘./src/views’)
- create a .pug template file in the views path using pug syntax (ie index.pug)
- app.get(‘/’, (req, res) => {
- //any code
- res.render(‘index’, { pugTemplateVar1: ‘some value’, pugVar2: ‘some val’, etc…})
- })
In javascript you can reuse the same function name in the same scope, as long as the functions have a different number of parameters.
you can even call the alternate signature within the function.
reminder
What are the schema types available for mongoose?
String
Number
Date
Buffer
Boolean
ObjectID
Array
Installing and setup steps for MongoDb locally.
Install MSI’s for MongoDB community, Mongo Shell, Mongo Tools, and Mongo Compass
Append the folder path for mongo.exe to the PATH System environment variable (this is just so you don’t have to move to this path in order to run mongo on the command line)
Make sure MongoDB is running in Services
When connecting you may need to use the 127.0.0.1:27017 instead of localhost
reminder
What are 8 comparison Operators in mongoose along with their meaning
reminder: these operators will be prefixed with $ during use.
eq (equal)
ne (not equal)
gt (greater than)
gte (greater than or equal to)
lt (less than)
lte (less than or equal to)
in (in)
nin (not in)
What are the 3 types of app Tests and their general meanings?
Unit Tests: Testing units of the app withOUT EXTERNAL dependencies
Integration Tests: Testing application WITH EXTERNAL dependencies
End to End Tests: Testing multiple units (ie classes) of an application together or as a whole. Another example is using selenium to automate a user interface test.
in Jest, what is the difference between using the method .toBe() vs .toEqual()
toBe will compare reference variables by reference as where toEqual will compare reference objects by their contained values.
for config.js what file name do you use for the config file that has global env settings. ie matches/pulls process.env values by property value name into the config object, no mater what NODE_ENV your in.
custom-environment-variables.json
1 What is the command to install the Nest CLI
2 What is the command to start a nest project?
- npm install -g @nestjs/cli
- nest new pathName
What are the 7 primative types in Typescript
string, number, boolean, null, undefined, void, symbol
What are the 4 object types in typescript?
functions, arrays, classes, and objects
A typescript object that is an array with a fixed structure. It resembles an object structure without property names by defining the value type of each index.
ie const pepsi: [string, boolean, number] = [‘brown’, true, 40]
index 0 represents the color of the drink
index 1 represents whether the drink is carbonated
index 2 represents the number of carbs
Tuple
How can you predefine a tuple structure for reuse when defining them.
type SomeStructure = [string, boolean, boolean, etcetera]
An interface (in Typescript) is a way to define an Object type. objects that receive an interface type are required to have all the properties of that interface. Not less, but the objects are allowed to have more properties.
Important note: With an object that has more properties than is defined in its interface, those additional properties become private inside the object. Basically, you cannot read any of the additional properties, only other properties inside the object can use these extra values using the ‘this’ keyword.
The above applies to function parameters that take an object based on an interface type. If you apply an interface to an instance of an object it will restrict you to only define properties that match the interface.
reminder
What do the modifiers private, protected, and public mean added to methods on a class?
Extra Note1: the child class can’t escalate the protection level up from that assigned in the parent.
Extra Note 2: If you add modifiers to the parameters in the constructor of a class, you do not need to set a ‘this’ property nor initialize the variable. Also, the same type of protection levels apply.
Private means the method can only be used within the class
Protected means the method can only be used in the parent and it’s child classes.
Public is default and means that the method can be used anywhere outside the class.
In classes that extend from a parent that takes initial values, you only need to call super if you need to define the constructor method to add additional parameters on the child class.
Basicallically, you don’t need to generate a constructor at all, as the constructor from the parent is called by default. But once you add a constructor for other reasons, the parent must be initialized by super.
reminder
What is a good website to get a list of ascii character info
www.asciitable.com
What are the two Type Guard opperators and the value types that each applies to (in a type guard role)?
typeof for string, boolean, number, symbol
instance of for every other value created with a constructor
To setup c# development in VS Code, you must:
Install the .Net SDK
Install the C# extension in VSCode
For .net 6 you need to add a setting to VS Code settings: “omnisharp.useModernNet”: true
reminder
To start a c# program in vscode.
to create project in current folder, run: dotnet new [type of project]
to get a list of project types, run: dotnet new -l
after creating project, if not promoted, go to command pallet and search for .Net Generate assets for build and debug, to add debugging files.
To run the project: dotnet run
reminder