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?