2

I am writing a client to talk to a server API in JavaScript. I have an OOP background but am trying to embrace modern EcmaScript.

So I started with this:

customerApi.js:

const baseUrl = "http://myapi";
export const getCustomers = () => { /* get customer code */ }
export const addCustomer = cust => { /* add customer code */ }
export const deleteCustomer = id => { /* delete customer code */ }

All the functions use the baseUrl variable.

Now I want to refactor so that the code that uses the customerApi module sets/passes in the baseUrl. I have come up the following-

Make it a class:

export default class customerApi {
 constructor(baseUrl) {
 this._baseUrl baseUrl;
 }
 getCustomers = () => { /* get customer code */ }
 addCustomer = cust => { /* add customer code */ }
 deleteCustomer = id => { /* delete customer code */ }
}

Pass the base URL into every method:

export const getCustomers = (baseUrl) => { /* get customer code */ }
export const addCustomer = (baseUrl,cust) => { /* delete customer code */ }
export const deleteCustomer = (baseUrl,id) => { /* add customer code */ }

Wrap in a function. I think this provides the client code the best API as you don't need to instantiate or pass the URL.

const moduleFn = baseUrl => (
 return {
 getCustomers: () => { /* get customer code */ }
 addCustomer: (cust) => { /* add customer code */ }
 deleteCustomer: (id) => { /* delete customer code */ }
 }
)
export default moduleFn;

What is the preferred/most common pattern to implement a "settable" variable on a module? Is there a better pattern?

asked Mar 28, 2019 at 13:58

1 Answer 1

1

Passing the URL into every method probably makes for an inconvenient user interface.

Your other proposed solutions (a class, an outer function) are both perfectly fine. They are also absolutely identical for all practical purposes. For users of your API they differ merely in whether they have to use the new keyword.

answered Mar 28, 2019 at 17:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.