최초 발행일 2020-06-03
Typescript: The Complete Developer's Guide [2020] 수업을 듣고 정리한 내용입니다.
reflect-metadata 패키지를 사용하여 메타데이터를 쓰고 읽는다.import 'reflect-metadata';
const plane = {
color: 'red'
};
// 이 코드는 plane 객체에 note 프로퍼티와 값 hi there을
// 숨겨진 프로퍼티(메타데이터)로 정의한다.
Reflect.defineMetadata('note', 'hi there', plane);
const note = Reflect.getMetadata('note', plane);
console.log(note);
// 이 코드는 plane 객체의 color 프로퍼티에 note 프로퍼티와 값 hi there을
// 숨겨진 프로퍼티(메타데이터)로 정의한다.
Reflect.defineMetadata('note', 'hi there2', plane, 'color');
const note2 = Reflect.getMetadata('note', plane, 'color');
console.log(note2);
class Plane {
color: string = 'red';
@markFunction
fly(): void {
console.log('vrrrrrrrrrrrrr');
}
}
function markFunction(target: Plane, key: string) {
Reflect.defineMetadata('secret', 123, target, key);
}
const secret = Reflect.getMetadata('secret', Plane.prototype, 'fly');
console.log(secret); //123
class Plane {
color: string = 'red';
@markFunction('HI THERE')
fly(): void {
console.log('vrrrrrrrrrrrrr');
}
}
function markFunction(secretInfo: string) {
return function markFunction(target: Plane, key: string) {
Reflect.defineMetadata('secret', secretInfo, target, key);
};
}
const secret = Reflect.getMetadata('secret', Plane.prototype, 'fly');
console.log(secret); //HI THERE
@printMetadata
class Plane {
color: string = 'red';
@markFunction('HI THERE')
fly(): void {
console.log('vrrrrrrrrrrrrr');
}
}
function markFunction(secretInfo: string) {
return function markFunction(target: Plane, key: string) {
Reflect.defineMetadata('secret', secretInfo, target, key);
};
}
//typeof Plane -> reference to the constructor function of the Plane class
function printMetadata(target: typeof Plane) {
for (let key in target.prototype) {
const secret = Reflect.getMetadata('secret', target.prototype, key);
console.log(secret); //HI THERE
}
}
앞으로 nodejs에 타입스크립트를 적용하며 만들어 나갈 형태는 다음과 같다.
@controller
class Plane {
color: string = 'red';
@get('/login')
fly(): void {
console.log('vrrrrrrrrrrrrr');
}
}
function get(path: string) {
return function markFunction(target: Plane, key: string) {
Reflect.defineMetadata('path', path, target, key);
};
}
//typeof Plane -> reference to the constructor funciton of the Plane class
function controller(target: typeof Plane) {
console.log(target.prototype);
for (let key in target.prototype) {
const path = Reflect.getMetadata('path', target.prototype, key);
console.log(path); // /login
const middleware = Reflect.getMetadata('middleware', target.prototype, key);
router.get(path, middleware, target.prototype[type]);
}
}
const secret = Reflect.getMetadata('path', Plane.prototype, 'fly');
console.log(secret); // /login