#Is there any sense in having checks across 3 layers?

1 messages · Page 1 of 1 (latest)

opaque charm
#

repository — for database (SQL) operations,

service — for additional validation and business logic,

controller — to receive input from the user via req/res.

pearl yacht
#

Yes, they all seems to make sense.

But what you can do, if you do those checks all the time, is to create some helper functions.

For the database, you could have several methods with the checks, and the right types
Example :

async function getOne<T>(query, params): Promise<T> {
  const results = await pool.query(query, params)
  if (!result.rows[0]) {
    throw new Error('Cannot find element')
  return result.rows[0]
}

// in your code
const user = await getOne<User>('SELECT ...', { id })

And for the controller, you can have some schema validation middleware, that will ensure you only get to your controller if you passed the right data, and generate the proper error otherwise.