Skip to content

Instantly share code, notes, and snippets.

@nukosuke
Last active February 26, 2019 09:17
Show Gist options
  • Save nukosuke/8f2b05b5c8a16881c7da5eb74884bffb to your computer and use it in GitHub Desktop.
Save nukosuke/8f2b05b5c8a16881c7da5eb74884bffb to your computer and use it in GitHub Desktop.
諸事情によりメソッド名を変更すると壊れるアプリケーションのためのメソッド名変更禁止Docorator
function StaffAction(args: { nameMustBe: string }) {
return (target: any, name: string, descriptor: PropertyDescriptor) => {
if (args.nameMustBe !== name) {
throw new Error(`
!!! FATAL: ${name}() !!!
Fixed method name has changed. This change will breake application.
Please revert the method name to "${args.nameMustBe}".
`);
}
};
}
class FixedMethods {
constructor() {
}
@StaffAction({ nameMustBe: "correctName" })
correctName() {
return;
}
@StaffAction({ nameMustBe: "mustBeName" })
invalidName() {
return;
}
}
const fixed = new FixedMethods();
// No error
fixed.correctName();
// Must throw error
fixed.invalidName();
@nukosuke
Copy link
Author

nukosuke commented Feb 26, 2019

2019-02-26 17 30 58

transpiled js

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
function StaffAction(args) {
    return function (target, name, descriptor) {
        if (args.nameMustBe !== name) {
            throw new Error("\n            \n            !!! FATAL: " + name + "() !!!\n            Fixed method name has changed. This change will broke application.\n            Please revert the method name to \"" + args.nameMustBe + "\".\n            ");
        }
    };
}
var FixedMethods = /** @class */ (function () {
    function FixedMethods() {
    }
    FixedMethods.prototype.correctName = function () {
        return;
    };
    FixedMethods.prototype.invalidName = function () {
        return;
    };
    __decorate([
        StaffAction({ nameMustBe: "correctName" })
    ], FixedMethods.prototype, "correctName", null);
    __decorate([
        StaffAction({ nameMustBe: "mustBeName" })
    ], FixedMethods.prototype, "invalidName", null);
    return FixedMethods;
}());
var fixed = new FixedMethods();
// No error
fixed.correctName();
// Must throw error
fixed.invalidName();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment