Created
May 10, 2017 09:24
-
-
Save ktutnik/f69e56fe9c2a0adf8b41e47d1c1af636 to your computer and use it in GitHub Desktop.
Route generator sederhana
This file contains 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
class StrategyBase { | |
next() { | |
return { type: "next" }; | |
} | |
exit(result) { | |
return { type: "exit", result: result }; | |
} | |
} | |
class DefaultStrategy extends StrategyBase { | |
transform(meta) { | |
return this.exit(`GET /${meta.controller}/${meta.action}`); | |
} | |
} | |
class DecoratedStrategy extends StrategyBase { | |
transform(meta) { | |
if (meta.decorator) { | |
return this.exit(meta.decorator); | |
} | |
return this.next(); | |
} | |
} | |
class ConventionStrategy extends StrategyBase { | |
transform(meta) { | |
switch (meta.action) { | |
case "add": | |
return this.exit(`POST /${meta.controller}`); | |
case "modify": | |
return this.exit(`PATCH /${meta.controller}/:id`); | |
default: | |
return this.next(); | |
} | |
} | |
} | |
class Generator { | |
constructor() { | |
this.transformers = [ | |
new DecoratedStrategy(), | |
new ConventionStrategy(), | |
new DefaultStrategy() | |
]; | |
} | |
generate(meta) { | |
for (let x of this.transformers) { | |
let result = x.transform(meta); | |
if (result.type == "exit") | |
return result.result; | |
} | |
} | |
} | |
let generator = new Generator(); | |
console.log(generator.generate({ controller: "user", action: "list" })); | |
console.log(generator.generate({ controller: "user", action: "add" })); | |
console.log(generator.generate({ controller: "user", action: "list", decorator: "GET /hello/world" })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment