primera pregunta aquí.
¿Alguien sabe cómo extender la respuesta en Opine (marco Deno) para que pueda crear respuestas personalizadas?
Por ejemplo, me gustaría crear:
res.success(message)Para que no necesite establecer códigos HTTP cada vez así:
res.setStatus(200).json({data: "success" });Intenté extender la respuesta como se hace aquí:https://deno.land/x/opine@2.1.5/test/units/app.response.test.ts
Este es mi código:
import { opine } from "https://deno.land/x/opine@2.1.4/mod.ts"; const app = opine(); (app.response as any).shout = function (str: string) { this.send(str.toUpperCase()); }; app.get("/", (req, res) => { res.shout("hello") }) app.listen(3000); console.log("Opine started on port 3000"); export { app };Pero cuando ejecuto el programa me sale:
error: TS2339 [ERROR]: Property 'shout' does not exist on type 'OpineResponse<any>'. res.shout("hello") ~~~~~Gracias.
Realmente no hay una forma "limpia" de hacer esto sin bifurcar la opinión y modificar las funciones y métodos que son fundamentales para la biblioteca.
Puede satisfacer al compilador afirmando los tipos en los sitios de invocación ( por ejemplo, usando any como en el archivo de prueba al que se vinculó ). Otro enfoque es usar una función de aserción como en el refactor de ejemplo de su código a continuación:
so-71990454.ts :
import { assert } from "https://deno.land/std@0.136.0/testing/asserts.ts"; import { type Opine, opine, type OpineResponse, } from "https://deno.land/x/opine@2.1.5/mod.ts"; // Define the type extensions here type ExtendedOpineResponse = { shout(body: string): void; }; // Implement the extensions here function extendOpineApp(app: Opine): void { // deno-lint-ignore no-explicit-any (app.response as any).shout = function (str: string) { this.send(str.toUpperCase()); }; } // Assert feature tests for each one in this function function assertIsExtendedResponse<T extends OpineResponse>( response: T, ): asserts response is T & ExtendedOpineResponse { assert( // deno-lint-ignore no-explicit-any typeof (response as any).shout === "function", 'Method "shout" not found on response', ); } export const app = opine(); // Invoke the extending function after creating the app extendOpineApp(app); app.get("/", (_req, res) => { assertIsExtendedResponse(res); res.shout("hello"); }); app.listen(3000); console.log("Opine started on port 3000");Puede ver que la verificación de tipo del módulo no produce errores de diagnóstico:
$ deno --version deno 1.21.0 (release, x86_64-unknown-linux-gnu) v8 10.0.139.17 typescript 4.6.2 $ deno check so-71990454.ts $ echo $? 0