Skip to content

Instantly share code, notes, and snippets.

@ktutnik
Created May 10, 2017 09:24
Show Gist options
  • Save ktutnik/f69e56fe9c2a0adf8b41e47d1c1af636 to your computer and use it in GitHub Desktop.
Save ktutnik/f69e56fe9c2a0adf8b41e47d1c1af636 to your computer and use it in GitHub Desktop.
Route generator sederhana
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