rest-hapi icon indicating copy to clipboard operation
rest-hapi copied to clipboard

Refactor functions to use default parameters/options object

Open JKHeadley opened this issue 7 years ago • 1 comments

See: https://gist.github.com/ericelliott/f3c2a53a1d4100539f71

Advantages

See: https://medium.com/javascript-scene/you-might-not-need-typescript-or-static-types-aa7cb670a77b

  • autocomplete and type inference with most IDEs
  • doesn't require passing Log objects for every call (although it's encouraged)
  • other non-required parameters (such as query) can be omitted
  • much easier to add/modify parameter list without making breaking changes (huge for project scalability)

Considerations

  • major breaking change
  • need to assert parameters/options exist and follow correct format (should do this anyway)

Examples

Ex1: https://github.com/JKHeadley/rest-hapi/blob/09d2045edc90adbb464ca5f79f935a40d9a181ee/utilities/handler-helper.js#L68

  • current:
function _list(model, query, Log)
  • proposed:
function _list({ model: {}, query: {}, Log: RestHapi.getLogger('list') })
  • usage:
let results = await RestHapi.list({ model: mongoose.model('user') })

Ex2: https://github.com/JKHeadley/rest-hapi/blob/09d2045edc90adbb464ca5f79f935a40d9a181ee/utilities/handler-helper.js#L692

  • current:
function _addOne(ownerModel, ownerId, childModel, childId, associationName, payload, Log)
  • proposed:
function _addOne({
ownerModel: {}, 
ownerId: '', 
childModel: {}, 
childId: '', 
associationName: '', 
payload: {}, 
Log: RestHapi.getLogger('addOne')

Ex3: https://github.com/JKHeadley/rest-hapi/blob/09d2045edc90adbb464ca5f79f935a40d9a181ee/utilities/handler-helper.js#L89

  • current:
query = await model.routeOptions.list.pre(query, request, Log)
  • proposed:
query = await model.routeOptions.list.pre({ query, request, Log })

This means middleware functions could be defined like so:

    routeOptions: {
      list: {
        pre: function (params) {
          let { query, request, Log } = params
          /* do work */
          return query
        }
      }
    },

JKHeadley avatar Jul 21 '18 00:07 JKHeadley

Handler portion resolved with https://github.com/JKHeadley/rest-hapi/pull/200

JKHeadley avatar Sep 13 '19 20:09 JKHeadley