Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lazy getters
import { makeFoo, makeBar } from "./providers.js"
/**
* Create property `name` on `obj` that will run `provider`'s factory method the first time
*/
function makeLazyGetter(obj, name, provider){
let value
Object.defineProperty(obj, name, {
get: function(){
if(!value){
value= factory()
}
return value
}
})
}
export function injectProvidersMiddleware(req){
makeLazyGetter(req, "foo", makeFoo)
makeLazyGetter(req, "bar", makeBar)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment