Skip to content

A DRYer way to import functions #6

@djfarrelly

Description

@djfarrelly

Extracting an idea from https://github.com/bufferapp/core-authentication-service/issues/15, what if we had a DRYer (don't repeat yourself) way to import a bunch of RPC functions?

Right now, the way we're doing things, we've set up projects to require 3 pieces in place:

  1. The rpc index file - ./src/rpc/index.js (example):
module.exports = {
  createAccount: require('./createAccount'),
  getAccount: require('./getAccount'),
}
  1. The require of all functions - usually in the main Express server's index.js file (example)
const {
  createAccount,
  getAccount,
} = require('./rpc')
  1. Registering the rpc functions (example)
  app.post(
    '/rpc',
    rpc(
      method('createAccount', createAccount),
      method('getAccount', getAccount),
    ),
    errorMiddleware,
  )

3.5. BONUS - Why do we need to use method('methodName', methodName)?


Question: - Why do we need to repeat ourselves so much?
Idea - Can we remove most of these steps by providing a simpler way to do this?

// idea 1
// we remove the ./rpc/index.js file and dynamically require all files in that directory
// if a string (path to files) is the first argument 
const { rpc, errorMiddleware } = require('buffer-rpc')

// Even this line of code says `rpc` 3 times 😁
app.post('/rpc', rpc('./rpc'), errorMiddleware)

// idea 2
// same as idea 1, but we use a load function to require all the rpc functions
const { rpc, loadFunctions, errorMiddleware } = require('buffer-rpc')

const functions = loadFunctions(path.join(__dirname, './rpc'))
app.post('/rpc', rpc(functions), errorMiddleware)

// idea 3
// make the error middleware automatic if you're already using `rpc()`
const { rpc } = require('buffer-rpc')

app.post('/rpc', rpc('./rpc'))

// idea 4
// what if we just assumed the rpc directory was the default arg?
const { rpc } = require('buffer-rpc')

app.post('/rpc', rpc())

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions