Created
July 10, 2015 17:44
-
-
Save ronco/ffaa1c7256990529068b to your computer and use it in GitHub Desktop.
Override mirage server endpoints helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let defaultMap = {}; | |
function getPathMap(verb) { | |
let verbPaths = defaultMap[verb]; | |
if (!verbPaths) { | |
verbPaths = {}; | |
defaultMap[verb] = verbPaths; | |
} | |
return verbPaths; | |
} | |
function getDefaultHandler(verb, path) { | |
let verbUpper = verb.toUpperCase(); | |
let verbPaths = getPathMap(verb); | |
let pretenderPath = `${server.namespace}${path}`; | |
if (verbPaths[path]) { | |
return verbPaths[path]; | |
} | |
// get default from pretender | |
verbPaths[path] = | |
server.pretender.registry[verbUpper].recognize(pretenderPath)[0].handler; | |
return verbPaths[path]; | |
} | |
export function overridePath(verb, path, ...args) { | |
verb = verb.toLowerCase(); | |
let verbPaths = getPathMap(verb); | |
// get default from pretender | |
getDefaultHandler(verb, path); | |
// register new handler with mirage | |
args.unshift(path); | |
server[verb].apply(server, args); | |
} | |
export function resetPath(verb, path) { | |
verb = verb.toLowerCase(); | |
let defaultHandler = getDefaultHandler(verb, path); | |
if (defaultHandler) { | |
// re-register default with pretender | |
server.pretender[verb](`${server.namespace}${path}`, defaultHandler); | |
} | |
} | |
export function overridePut(...args) { | |
args.unshift('put'); | |
overridePath.apply(this, args); | |
} | |
export function overrideGet(...args) { | |
args.unshift('get'); | |
overridePath.apply(this, args); | |
} | |
export function overridePost(...args) { | |
args.unshift('post'); | |
overridePath.apply(this, args); | |
} | |
export function overrideDelete(...args) { | |
args.unshift('delete'); | |
overridePath.apply(this, args); | |
} | |
export function resetPut(...args) { | |
args.unshift('put'); | |
resetPath.apply(this, args); | |
} | |
export function resetGet(...args) { | |
args.unshift('get'); | |
resetPath.apply(this, args); | |
} | |
export function resetPost(...args) { | |
args.unshift('post'); | |
resetPath.apply(this, args); | |
} | |
export function resetDelete(...args) { | |
args.unshift('delete'); | |
resetPath.apply(this, args); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment