1.0.0 • Published 5 years ago

formationnodenovembre v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
5 years ago

Node.js training (2018 nov. 12-14)

Practical info

Trainer

  • Nicolas Chambrier
  • @naholyr
  • naholyr@gmail.com

ES6: Spreading operator

https://node.green/

Rest parameters:

const foo = (a, b, c, ...rest) {
  rest // [4, 5, 6]
}

foo(1, 2, 3, 4, 5, 6)

Spread arguments:

const array = [1, 2, 3, 4, 5, 6]
foo(...array)

Spread operator (array, object)

const a1 = [1, 2, 3]
const a2 = [4, 5, 6]
const a = [0, ...a1, ...a2, 7]

const o1 = { x: 1, y: 1 }
const o2 = { x: 2, z: 2 }
const o = { ...o1, ...o2, w: 3 }
// {x: 1, y: 1, x: 2, z: 2, w: 3}
// {x: 2, y: 1, z: 2, w: 3}

Attention: shallow copy

const data = { users: [{ name: 'Bob' }, { name: 'John' }] }

const users2 = [...data.users, { name: 'Jesus' }]
users2[0].name = 'Toto'

data.users[0].name // 'Toto'

bodyParser.urlencoded extended

"a=1&b=2&c=3"
{ a: '1', b: '2', c: '3' }

"person.name=toto&person.age=33"
false → { "person.name": "toto", "person.age": '33' }
true → { person: { name: 'toto', age: '33' } }

"a=1&a=2"
false → { a: ['1', '2'] }
true → { a: '2' }

"a[]=1&a[]=2"
false → { "a[]": ['1', '2'] }
true → { a: ['1', '2'] }

Express sessions

Usually: connect-redis (we used sessionstore)

DO NOT USE SESSION STORE BECAUSE OF https://github.com/adrai/sessionstore/issues/49

import session from 'express-session'
import connectRedis from 'connect-redis'

const RedisStore = connectRedis(session)

app.use(session({
  ...
  store: new RedisStore({ host, port, ... })
}))

Redis in Docker

To avoid some warnings (not really necessary for dev machine):

# On host

echo 'vm.overcommit_memory = 1' | sudo tee -a /etc/sysctl.conf
sudo sysctl vm.overcommit_memory=1

echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
# Create container
docker run --name=redis -v redis:/data -d -p 6379:6379 redis redis-server

Then just run docker start redis and docker stop redis to start/stop service.

docker logs -f redis to watch logs.

Mocha + ES6 modules

  • Test files must end with .js because mocha will require() them instead of importing them
  • Use esm module to make it work

Quizou

API : https://opentdb.com/api.php?amount=50&difficulty=easy&type=multiple

{
  "response_code":0,
  "results": [
    {
      "category":"Entertainment: Film",
      "type":"multiple",
      "difficulty":"easy",
      "question":"Which of the following is not the name of a 'Bond Girl'? ",
      "correct_answer":"Vanessa Kensington",
      "incorrect_answers":["Pam Bouvier","Mary Goodnight","Wai Lin"]
    },
    …
  ]
}
1.0.0

5 years ago