.
Last active
November 23, 2023 22:46
-
-
Save johncovv/386da4c7d7eb6276a88accfa3064aa67 to your computer and use it in GitHub Desktop.
Typescript Decorators
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
function meuDecorator<T extends {new(...args: any[]): {}}>(construtor: T) { | |
return class extends construtor { | |
meuMetodoAdicional() { | |
console.log("Este é um método adicional adicionado pelo decorator"); | |
} | |
} | |
} | |
function meuOutroDecorator<T extends {new(...args: any[]): {}}>(construtor: T) { | |
constructor.prototype.meuOutroMetodoAdicional = function() { | |
console.log("Este é um outro método adicional adicionado pelo decorator"); | |
} | |
} |
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
@meuDecorator | |
@meuOutroDecorator | |
class MinhaClasse { | |
constructor(private valor: string) {} | |
meuMetodo() { | |
console.log(`Valor: ${this.valor}`); | |
} | |
} |
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
class Login { | |
constructor() {} | |
@AllowedMethod("POST") | |
async exec(req: Request, res: Response) { | |
try { | |
const { username, password } = req.body; | |
// handle login | |
return res.status(200).json({ ok: true, user: {} }); | |
} catch (error) { | |
console.log(`Error: `, error); | |
} | |
} | |
} | |
class GetUser { | |
constructor() {} | |
@AllowedMethod("GET") | |
async exec(req: Request, res: Response) { | |
try { | |
const { id } = req.body; | |
// handle get user | |
return res.status(200).json({ ok: true, user: {} }); | |
} catch (error) { | |
console.log(`Error: `, error); | |
} | |
} | |
} |
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
// Limitador de métodos para request | |
import { Request, Response } from "express"; | |
export function AllowedMethod(method: "POST" | "GET" | "PUT" | "PATCH" | "DELETE") { | |
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { | |
const originalMethod = descriptor.value; | |
descriptor.value = async function (req: Request, res: Response): Promise<void | Response> { | |
if (req.method !== method) { | |
return res.status(405).json({ ok: false, message: "Method not allowed" }); | |
} | |
return originalMethod.apply(this, [req, res]); | |
}; | |
return descriptor; | |
}; | |
} |
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
// Exemplo de decorator puro para funções (controle de acesso) | |
const user = { | |
name: "John Covv", | |
email: "[email protected]", | |
roles: ['user'] | |
} | |
function guard(allowedRoles: Array<'admin' | 'user'>, callback: Function) { | |
if (!user || !user.roles || !user.roles.some((role) => allowedRoles.includes(role as any))) { | |
throw new Error('acesso negado'); | |
} | |
return callback(); | |
} | |
guard(['user'], () => console.log('acesso concedido')); | |
//esperado: log "acesso concedido" | |
guard(['admin'], () => console.log('acesso concedido')); | |
//esperado: disparar o erro "acesso negado" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment