ShinGecko / neKo-Api

Api provided to support the innovative chat neKo
ISC License
0 stars 1 forks source link

Talking about Thinky #4

Closed Shenrak closed 7 years ago

Shenrak commented 7 years ago

How exactly should I get the result ?

let auth = async (email, password) => {
  let result
  models.users.filter({
    email: email,
    password: password,
  }).run().then(user => result = user)
  return result
}

module.exports.auth = async function (ctx) {
  console.log(auth(ctx.request.body.email, ctx.request.body.password))
  if (auth(ctx.request.body.email, ctx.request.body.password)) {
    ctx.status = 200
  } else {
    ctx.set('Content-Type', 'text/plain')
    ctx.status = 401
    ctx.body = 'Wrong Login or Password'
  }
  return true
}

I know it's asynchronous so actually I'm wondering how i should get chat's in the .then(user) callback

justinrlle commented 7 years ago

Two things: about auth, and how to use it.

auth

Because it's asynchronous, the moment you do return result isn't guaranteed to be after the .then. you can do two things here:

usage

You need to await on the auth function. Like I said earlier, auth will return a Promise. So if you do console.log(auth(ctx.... )), it will log Promise <pending...>. And the if will also test on a Promise rather than a value. So you can do the following for example:

module.exports.auth = async function (ctx) {
  const user = await auth(ctx.request.body.email, ctx.request.body.password);
  console.log(user)
  if (user) {
    ctx.status = 200
  } else {
    ctx.set('Content-Type', 'text/plain')
    ctx.status = 401
    ctx.body = 'Wrong Login or Password'
  }
  return true
}

Here, contrarly to the precedent case (the auth function), async/await help for the clarification of the code greatly.

Side notes

In fact, the first function, you should use const instead of let, and if you take the path of the Promise (I highly recommend it), you can write the function in a simpler way:

const auth = (email, password) =>
  models.users.filter({
    email: email,
    password: password,
  }).run()
justinrlle commented 7 years ago

Btw, about that part

  } else {
    ctx.set('Content-Type', 'text/plain')
    ctx.status = 401
    ctx.body = 'Wrong Login or Password'
  }

You should here use the new HttpError class:

throw new HttpError('Wrong Login or Password', 401)
Shenrak commented 7 years ago

You really should write tutorials mate.