Skip to content

Instantly share code, notes, and snippets.

@SevenOutman
Created April 18, 2021 10:27
Show Gist options
  • Save SevenOutman/df3f3033b9e2868a4c9ba548cebd5bb2 to your computer and use it in GitHub Desktop.
Save SevenOutman/df3f3033b9e2868a4c9ba548cebd5bb2 to your computer and use it in GitHub Desktop.
// Expected output:
//
// const oa = createBuilder('/oa')
// oa() /oa
// oa.meetingroom() /oa/meetingroom
// oa.meetingroom.add() /oa/meetingroom/add
//
// Yep it's a endpoint builder and can evolve to be a api caller
function createEndpointBuilder(base) {
const parent = function () {
return base
}
return new Proxy(parent, {
get: function(target, prop, receiver) {
// TODO memorize
return createEndpointBuilder(base + '/' + prop);
}
})
}
const oa = createEndpointBuilder('/oa')
console.log(oa())
console.log(oa.meetingroom())
console.log(oa.meetingroom.add())
function createEndpointCaller(baseUrl) {
function callEndpoint(data) {
console.log('Endpoint ' + baseUrl + ' is called with data ' + JSON.stringify(data))
}
return new Proxy(callEndpoint, {
get: function(target, prop, receiver) {
return createEndpointCaller(baseUrl + '/' + prop);
}
})
}
const api = {
oa: createEndpointCaller('/oa')
}
api.oa({ message: 'some message' })
api.oa.meetingroom({ message: 'some message' })
api.oa.meetingroom.add({ message: 'some message' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment