0

What is a practical way to check if a user is already in the db before trying to insert the information for a "new user"

Here is my get user by id and insert function:

const getUserById = (request, response) => {
    const id = parseInt(request.params.attuid)

    pg.query('SELECT * FROM geodate.users WHERE attuid = $1', [attuid], (err, res) => {
        if (err) {
            return next(err)
        }
        response.status(200).json(results.rows)
    })
}


const createUser = (request, response) => {
    const attuid = request.body[0].attuid

    pg.query('INSERT INTO geodata.users (attuid, num_queries,created_date,modified_date) VALUES ($1,$2,$3,$4) RETURNING *', [attuid, 0, moment(new Date()), moment(new Date())], (error, results) => {
        if (error) {
            throw error
        }
        response.status(201).send(`User added with ID: ${results.rows[0].attuid}`)
    })
}

Thanks

1 Answer 1

1

rf guy, Nice shades. First select the user from the geodata.users table. If the user exists, you should not add the user. I don't use pg to query postgres, so I really don't know how it works, but you should be able to do this:

const createUser = (request, response) => {   const attuid = request.body[0].attuid

  pg.query('SELECT * FROM geodate.users WHERE attuid = $1', [attuid], (err, res)=> {
    if (err) {
        return next(err)
    }
      if(results.rows > 0)
      {

        pg.query('INSERT INTO geodata.users (attuid, num_queries,created_date,modified_date) VALUES ($1,$2,$3,$4) RETURNING
*', [attuid, 0, moment(new Date()), moment(new Date())], (error, results) => {
          if (error) {
              throw error
          }
          response.status(201).send(`User added with ID: ${results.rows[0].attuid}`)
      })

      }
      else{
    response.status(200).json({"message": "Ha! you are already in the db, silly"})
      } }) }
Sign up to request clarification or add additional context in comments.

3 Comments

Hey, thanks Daniel. I updated my code above with my getuserbyid function. How do I call that before trying to insert the user?
That works perfect for what I need. Thank you. I was definitely over thinking it.
@rfguy ya, overthinking happens alot in this biz.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.