diff --git a/index.ts b/index.ts index 1da9da5..23861da 100644 --- a/index.ts +++ b/index.ts @@ -1,5 +1,6 @@ import { Kernel, Module, modules } from "nodefony"; - +import { controllers } from "@nodefony/framework"; +import AppController from "./nodefony/controllers/AppController"; import config from "./nodefony/config/config"; import http from "@nodefony/http"; import security from "@nodefony/security"; @@ -15,6 +16,7 @@ import sequelize from "@nodefony/sequelize"; "@nodefony/framework", "@nodefony/sequelize", ]) +@controllers([AppController]) class App extends Module { /** * Constructs an instance of the App class. diff --git a/nodefony/controllers/AppController.ts b/nodefony/controllers/AppController.ts new file mode 100644 index 0000000..f53517b --- /dev/null +++ b/nodefony/controllers/AppController.ts @@ -0,0 +1,72 @@ +//import { Service, Container, Module } from "nodefony"; +import { inject, Fetch } from "nodefony"; +import { DefineRoute, DefineController, Controller } from "@nodefony/framework"; +import { ContextType } from "@nodefony/http"; + +class AppController extends Controller { + static override basepath: string = "/app"; + constructor( + context: ContextType, + @inject("Fetch") private fetch: Fetch + ) { + super("app", context); + } + + async initialize() { + //console.log("passs initialize"); + //await this.startSession(); + return this; + } + + @DefineRoute("route1", { path: "/", method: "GET" }) + async method1() { + console.log("call method", this.fetch.library); + //await this.startSession(); + return this.renderJson({ foo: "bar" }); + } + + @DefineRoute("route3", { method: "DELETE" }) + method3() { + console.log("call method3", this.route); + } + + @DefineRoute("route2", { path: "/add", requirements: { methods: "POST" } }) + method2() { + console.log("call method2"); + return this.renderJson({ foo: "bar" }); + } + + @DefineRoute("route4", { + path: "/add/{name}", + requirements: { methods: ["GET", "POST"] }, + defaults: { name: "cci" }, + }) + method4(name: string) { + console.log("call method4", name, this.route); + return this.renderJson({ name }); + } + + @DefineRoute("route6", { + path: "/ele/{metier}/{format}/add", + defaults: { format: "cci" }, + }) + method6() { + console.log("other route for app"); + return this.renderJson({ foo: "bar" }); + } + @DefineRoute("route7", { + path: "/ele/{metier}/{format}/{method}/add", + }) + method7(metier: string, format: string, method: string) { + return this.renderJson({ metier, format, method }); + } + + @DefineRoute("route5", { + path: "*", + }) + method5() { + console.log("other route for app"); + } +} + +export default AppController; diff --git a/src/nodefony/src/kernel/Kernel.ts b/src/nodefony/src/kernel/Kernel.ts index 25954ce..ad3a474 100644 --- a/src/nodefony/src/kernel/Kernel.ts +++ b/src/nodefony/src/kernel/Kernel.ts @@ -96,7 +96,7 @@ export interface FilterInterface { } export interface ServiceWithInitialize extends Service { - initialize?(module: Module): Promise; + initialize?(module?: Module): Promise; } export interface ServiceConstructor { diff --git a/src/packages/@nodefony/framework/index.ts b/src/packages/@nodefony/framework/index.ts index 412001e..5b2f20b 100644 --- a/src/packages/@nodefony/framework/index.ts +++ b/src/packages/@nodefony/framework/index.ts @@ -1,13 +1,15 @@ import { Service, Kernel, Module, services } from "nodefony"; import config from "./nodefony/config/config"; import Router, { TypeController } from "./nodefony/service/router"; -import test from "./nodefony/controller/testController"; import Route from "./nodefony/src/Route"; import Controller from "./nodefony/src/Controller"; import Resolver from "./nodefony/src/Resolver"; -import { controllers } from "./nodefony/decorators/routerDecorators"; +import { + controllers, + DefineRoute, + DefineController, +} from "./nodefony/decorators/routerDecorators"; -@controllers([test]) @services([Router]) class Framework extends Module { constructor(kernel: Kernel) { @@ -16,5 +18,12 @@ class Framework extends Module { } export default Framework; - -export { Route, Controller, Resolver, Router, controllers }; +export { + Controller, + Route, + Router, + Resolver, + DefineRoute, + DefineController, + controllers, +}; diff --git a/src/packages/@nodefony/framework/nodefony/controller/testController.ts b/src/packages/@nodefony/framework/nodefony/controller/testController.ts deleted file mode 100644 index a05b197..0000000 --- a/src/packages/@nodefony/framework/nodefony/controller/testController.ts +++ /dev/null @@ -1,62 +0,0 @@ -//import { Service, Container, Module } from "nodefony"; -import { inject, Fetch } from "nodefony"; -import { route, controller } from "../decorators/routerDecorators"; -import Controller from "../src/Controller"; -import { Context } from "@nodefony/http"; - -class ExampleController extends Controller { - static override basepath: string = "/base"; - constructor( - context: Context, - @inject("Fetch") private fetch: Fetch - ) { - super("test", context); - } - - @route("route1", { path: "/", method: "GET" }) - method() { - console.log("call method", this.fetch.library); - } - - @route("route2", { path: "/add", method: "POST" }) - method2() { - console.log("call method2"); - } - - @route("route3", { method: "DELETE" }) - method3() { - console.log("call method3"); - } - - @route("route4", { - path: "/add/{name}", - method: ["GET", "POST"], - defaults: { name: "cci" }, - }) - method4() { - console.log("call method4"); - } - - @route("route6", { - path: "/ele/{metier}/{format}/add", - defaults: { format: "cci" }, - }) - method6() { - console.log("other route for base"); - } - @route("route7", { - path: "/ele/{metier}/{format}/{method}/add", - }) - method7() { - console.log("other route for base"); - } - - @route("route5", { - path: "*", - }) - method5() { - console.log("other route for base"); - } -} - -export default ExampleController; diff --git a/src/packages/@nodefony/framework/nodefony/decorators/routerDecorators.ts b/src/packages/@nodefony/framework/nodefony/decorators/routerDecorators.ts index bf265ca..0dc6912 100644 --- a/src/packages/@nodefony/framework/nodefony/decorators/routerDecorators.ts +++ b/src/packages/@nodefony/framework/nodefony/decorators/routerDecorators.ts @@ -7,7 +7,7 @@ import { ControllerConstructor } from "../src/Route"; type Constructor = new (...args: any[]) => T; -function controller(name: string, options: Record) { +function DefineController(name: string, options: Record) { return function (controller: any) { const constructor = controller.constructor; const className = controller.name; @@ -58,7 +58,7 @@ function controllers( * console.log("call method"); * } */ -function route(name: string, options: RouteOptions) { +function DefineRoute(name: string, options: RouteOptions) { return function ( target: any, propertyKey: string, @@ -96,4 +96,4 @@ function route(name: string, options: RouteOptions) { }; } -export { route, controller, controllers }; +export { DefineRoute, DefineController, controllers }; diff --git a/src/packages/@nodefony/framework/nodefony/service/router.ts b/src/packages/@nodefony/framework/nodefony/service/router.ts index 0d4a7ac..44f3023 100644 --- a/src/packages/@nodefony/framework/nodefony/service/router.ts +++ b/src/packages/@nodefony/framework/nodefony/service/router.ts @@ -7,7 +7,7 @@ import { injectable, } from "nodefony"; import Route, { RouteOptions } from "../src/Route"; -import { HttpKernel, Context } from "@nodefony/http"; +import { HttpKernel, Context, ContextType } from "@nodefony/http"; import Resolver from "../src/Resolver"; import Controller from "../src/Controller"; export type TypeController = new (...args: any[]) => T; @@ -30,32 +30,9 @@ class Router extends Service { module.notificationsCenter as Event, module.options.router ); - - // this.kernel?.once("onReady", () => { - // console.log(routes); - // const myRoute: Route = routes[0]; - // if (myRoute) { - // if (myRoute.controller && myRoute.classMethod) { - // const inst = new myRoute.controller(module); - // const methodKey = myRoute.classMethod as keyof typeof inst; - // if (typeof inst[methodKey] === "function") { - // (inst[methodKey] as Function)(); - // } - // console.log("################################"); - // this.matchRoutes("/base/add/ddddd"); - // console.log("################################"); - // this.matchRoutes("/base/ele/sboob/kdskdkd/add"); - // console.log("################################"); - // this.matchRoutes("/base/add/"); - // console.log("################################"); - // this.matchRoutes("/base/ele/sboob/kdskdkd/mymethos/add"); - // console.log("################################"); - // } - // } - // }); } - resolve(context: Context): Resolver { + resolve(context: ContextType): Resolver { const resolver = new Resolver(context); for (let i = 0; i < routes.length; i++) { try { diff --git a/src/packages/@nodefony/framework/nodefony/src/Controller.ts b/src/packages/@nodefony/framework/nodefony/src/Controller.ts index c67ef07..39cbbd5 100644 --- a/src/packages/@nodefony/framework/nodefony/src/Controller.ts +++ b/src/packages/@nodefony/framework/nodefony/src/Controller.ts @@ -1,14 +1,154 @@ -import { Service, Module, Container, Event } from "nodefony"; -import { Context } from "@nodefony/http"; +import { Service, Module, Container, Event, typeOf } from "nodefony"; +import Route from "./Route"; +import { + contextRequest, + contextResponse, + Context, + HTTPMethod, + HttpRequest, + Http2Request, + Session, + ContextType, +} from "@nodefony/http"; +import { HttpContext } from "@nodefony/http"; class Controller extends Service { static basepath: string = "/"; - constructor(name: string, context: Context) { + route?: Route | null = null; + request: contextRequest = null; + response: contextResponse = null; + context?: ContextType; + session?: Session | null; + sessionAutoStart: string | null = null; + method?: HTTPMethod; + queryGet: Record = {}; + query: Record = {}; + queryFile: any[] = []; + queryPost: Record = {}; + constructor(name: string, context: ContextType) { super( name, context.container as Container, context.notificationsCenter as Event ); + this.setContext(context); + } + setContextJson(encoding: BufferEncoding = "utf-8") { + return this.context?.setContextJson(encoding); + } + + async render( + view: string | Object, + param: Record | BufferEncoding = {} + ) { + if (!this.response) { + throw new Error( + "WARNING ASYNC !! RESPONSE ALREADY SENT BY EXPCEPTION FRAMEWORK" + ); + } + try { + switch (typeOf(view)) { + case "string": + return await this.renderView( + view as string, + param as Record + ); + default: + return this.renderJson(view as Object, param as BufferEncoding); + } + } catch (e) { + throw e; + } + } + + async renderView(view: string, param: Record = {}) { + return view; + } + + async renderJson( + obj: Record, + status?: string | number, + headers?: Record + ) { + let data = null; + try { + data = JSON.stringify(obj); + if (!this.response) { + throw new Error( + "WARNING ASYNC !! RESPONSE ALREADY SENT BY EXPCEPTION FRAMEWORK" + ); + } + this.response.setBody(data); + this.setContextJson(); + if (headers) { + this.response.setHeaders(headers); + } + if (status) { + this.response.setStatusCode(status); + } + return (this.context as HttpContext)?.send(data); + } catch (e) { + this.log(e, "ERROR"); + throw e; + } + } + + setRoute(route: Route): Route { + return (this.route = route); + } + + setContext(context: ContextType) { + const request = context.request as HttpRequest | Http2Request; + this.context = context; + this.method = this.context.method as HTTPMethod; + this.response = this.context.response; + this.request = this.context.request; + this.queryGet = request?.queryGet; + this.query = request?.query; + this.queryFile = request?.queryFile; + this.queryPost = request?.queryPost; + this.once("onRequestEnd", () => { + this.query = request?.query; + this.queryFile = request?.queryFile; + this.queryPost = request?.queryPost; + }); + this.session = this.getSession(); + } + + startSession(sessionContext?: string) { + const sessionService = this.get("sessions"); + // is subRequest + // if (this.context.parent) { + // return this.getSession(); + // } + if (!this.context?.requestEnded || this.context?.security) { + return (this.sessionAutoStart = + sessionService.setAutoStart(sessionContext)); + } + return sessionService.start(this.context, sessionContext); + } + + getSession(): Session | undefined | null { + return this.context?.session; + } + getFlashBag(key: string) { + const session = this.getSession(); + if (session) { + return session.getFlashBag(key); + } + this.log("getFlashBag session not started !", "ERROR"); + return null; + } + setFlashBag(key: string, value: any) { + const session = this.getSession(); + if (session) { + return session.setFlashBag(key, value); + } + return null; + } + + addFlash(key: string, value: any) { + return this.setFlashBag(key, value); } } diff --git a/src/packages/@nodefony/framework/nodefony/src/Resolver.ts b/src/packages/@nodefony/framework/nodefony/src/Resolver.ts index 4a869d0..47932b0 100644 --- a/src/packages/@nodefony/framework/nodefony/src/Resolver.ts +++ b/src/packages/@nodefony/framework/nodefony/src/Resolver.ts @@ -8,21 +8,28 @@ import { inject, } from "nodefony"; //import Router from "../service/router"; -import { Context, HttpError } from "@nodefony/http"; +import { Context, HttpError, ContextType } from "@nodefony/http"; import Route, { ControllerConstructor } from "./Route"; import BlueBird from "bluebird"; +import Controller from "./Controller"; +import { ServiceWithInitialize } from "nodefony"; //import { ServiceConstructor } from "nodefony"; +export interface ControllerWithInitialize { + initialize(controler: Controller): Promise; +} + class Resolver extends Service { injector: Injector; controller: ControllerConstructor | null = null; actionName?: string; action?: Function; - context: Context; + context: ContextType; route: Route | null = null; resolve: boolean = false; + variables: any[] = []; exception?: HttpError | Error | null; - constructor(context: Context) { + constructor(context: ContextType) { super( "RESOLVER", context.container as Container, @@ -32,10 +39,11 @@ class Resolver extends Service { this.injector = this.get("injector"); } - match(route: Route, context: Context) { + match(route: Route, context: ContextType) { try { const match = route.match(context); if (match) { + this.variables = match; this.route = route; this.controller = route.controller as ControllerConstructor; this.actionName = route.classMethod; @@ -47,33 +55,43 @@ class Resolver extends Service { } } - newController(context?: Context) { + async newController(context?: ContextType): Promise { if (this.controller) { - //const controller = new this.controller(context || this.context); const controller = this.injector.instantiate( this.controller, context || this.context ); - this.set("controller", controller); - return controller; + if (controller) { + this.set("controller", controller); + if ( + "initialize" in controller && + typeof controller.initialize === "function" + ) { + await controller.initialize(); + return controller as Controller; + } + return controller as Controller; + } } throw new Error(`Route Controller not found`); } - callController(data: any[] = [], reload: boolean = false) { + async callController(data: any[] = [], reload: boolean = false) { try { let controller = this.get("controller"); if (!controller || reload) { - controller = this.newController(); + controller = await this.newController(); } this.set("action", this.action); + this.set("route", this.route); + controller.setRoute(this.route); const methodKey = this.actionName as keyof typeof controller; + const ele = [...this.variables, ...data]; if (typeof controller[methodKey] === "function") { - this.action = controller[methodKey] as Function; - return (controller[methodKey] as Function)(); + return (controller[methodKey] as Function)(...ele); } if (this.action) { - return this.returnController(this.action(...data)); + return this.returnController(this.action(...ele)); } throw new Error(`Route Action not found`); } catch (e) { @@ -88,6 +106,7 @@ class Resolver extends Service { case result instanceof BlueBird: case isPromise(result): default: + this.context.waitAsync = true; } } } diff --git a/src/packages/@nodefony/framework/nodefony/src/Route.ts b/src/packages/@nodefony/framework/nodefony/src/Route.ts index 404cca6..4a78d29 100644 --- a/src/packages/@nodefony/framework/nodefony/src/Route.ts +++ b/src/packages/@nodefony/framework/nodefony/src/Route.ts @@ -4,6 +4,7 @@ import { SchemeType, HttpError, WebsocketContext, + ContextType, } from "@nodefony/http"; import { createHash } from "node:crypto"; import { typeOf } from "nodefony"; @@ -133,12 +134,13 @@ class Route { this.method = obj.method as HTTPMethod; this.setHostname(obj.host); this.setDefaults(obj.defaults); + this.requirements = obj.requirements || {}; this.compile(); } this.generateId(); } - match(context: Context) { + match(context: ContextType) { let res; if (context.request && context.request.url && this.pattern) { res = context.request.url.pathname.match(this.pattern as RegExp); @@ -213,14 +215,11 @@ class Route { return; } let pattern = this.path.replace(REG_ROUTE, replaceCallback.bind(this)); - //console.log("PASASAS", pattern); if (pattern[pattern.length - 1] === "*") { pattern = pattern.replace(REG_REPLACE, "\\$1").replace(/\*/g, "(.*)/?"); } else { pattern = pattern.replace(REG_REPLACE, "\\$1"); } - //console.log("PASASAS => ", pattern); - //this.pattern = new RegExp(`^${pattern}[/]?$`, "i"); this.pattern = new RegExp(`^${pattern}$`, "i"); return this.pattern; } @@ -297,7 +296,7 @@ class Route { this.host = hostname; } - matchHostname(context: Context) { + matchHostname(context: ContextType) { if (this.host) { if (this.host === context.domain) { return true; @@ -336,7 +335,7 @@ class Route { hasRequirements(): number { return Object.keys(this.requirements).length; } - matchRequirements(context: Context) { + matchRequirements(context: ContextType) { if (this.hasRequirements()) { for (const i in this.requirements) { switch (i) { diff --git a/src/packages/@nodefony/http/nodefony/service/http-kernel.ts b/src/packages/@nodefony/http/nodefony/service/http-kernel.ts index 1fb5def..bc06a9c 100644 --- a/src/packages/@nodefony/http/nodefony/service/http-kernel.ts +++ b/src/packages/@nodefony/http/nodefony/service/http-kernel.ts @@ -372,7 +372,7 @@ class HttpKernel extends Service { } return resolve(context); } catch (e) { - return this.onError(e as Error, context as Context).catch((e) => { + return this.onError(e as Error, context as ContextType).catch((e) => { this.log(e, "CRITIC"); return reject(e); }); diff --git a/src/packages/@nodefony/http/nodefony/service/sessions/sessions-service.ts b/src/packages/@nodefony/http/nodefony/service/sessions/sessions-service.ts index 712a1da..85d9886 100644 --- a/src/packages/@nodefony/http/nodefony/service/sessions/sessions-service.ts +++ b/src/packages/@nodefony/http/nodefony/service/sessions/sessions-service.ts @@ -19,8 +19,8 @@ import HttpKernel, { } from "../http-kernel"; import Context, { HTTPMethod } from "../../src/context/Context"; import Session, { OptionsSessionType } from "../../src/session/session"; -import Http2Resquest from "../../src/context/http2/Request"; -import HttpResquest from "../../src/context/http/Request"; +import Http2Request from "../../src/context/http2/Request"; +import HttpRequest from "../../src/context/http/Request"; import url from "node:url"; import Certificate from "../../service/certificates"; import { createHash } from "node:crypto"; @@ -207,7 +207,7 @@ class SessionsService extends Service { try { context.session = session; const method = context.method as HTTPMethod; - const request = context.request as HttpResquest | Http2Resquest; + const request = context.request as HttpRequest | Http2Request; if (method !== "WEBSOCKET" && request && request.request) { request.request.session = session; } diff --git a/src/packages/@nodefony/http/nodefony/src/context/Context.ts b/src/packages/@nodefony/http/nodefony/src/context/Context.ts index d75dd02..511907c 100644 --- a/src/packages/@nodefony/http/nodefony/src/context/Context.ts +++ b/src/packages/@nodefony/http/nodefony/src/context/Context.ts @@ -13,8 +13,8 @@ import HttpKernel, { ContextType, ServerType } from "../../service/http-kernel"; import HttpResponse from "./http/Response"; import Http2Response from "./http2/Response"; import WebsocketResponse from "./websocket/Response"; -import HttpResquest from "./http/Request"; -import Http2Resquest from "./http2/Request"; +import HttpRequest from "./http/Request"; +import Http2Request from "./http2/Request"; import SessionsService from "../../service/sessions/sessions-service"; import clc from "cli-color"; //import http from "node:http"; @@ -26,8 +26,8 @@ import HttpError from "../errors/httpError"; const colorLogEvent = clc.cyan.bgBlue("EVENT CONTEXT"); export type contextRequest = - | HttpResquest - | Http2Resquest + | HttpRequest + | Http2Request | websocket.request | null; export type contextResponse = @@ -52,6 +52,7 @@ export type Cookies = Record; class Context extends Service { secure: boolean = false; + security: any = null; cleaned: boolean = false; isControlledAccess: boolean = false; validDomain: boolean = false; @@ -76,6 +77,7 @@ class Context extends Service { session: Session | null | undefined = null; cookieSession: Cookie | null | undefined = null; user: any = null; + waitAsync: boolean = false; constructor(container: Container, type: ServerType) { super(`${type} CONTEXT`, container); this.type = type; @@ -203,6 +205,7 @@ class Context extends Service { parseCookies(): void { return cookiesParser(this); } + setContextJson(encoding: BufferEncoding = "utf-8"): void {} } export default Context; diff --git a/src/packages/@nodefony/http/nodefony/src/context/http/HttpContext.ts b/src/packages/@nodefony/http/nodefony/src/context/http/HttpContext.ts index d3032fb..7dd878a 100644 --- a/src/packages/@nodefony/http/nodefony/src/context/http/HttpContext.ts +++ b/src/packages/@nodefony/http/nodefony/src/context/http/HttpContext.ts @@ -1,24 +1,24 @@ import { ServerType, - httpRequest, - httpResponse, + //httpRequest, + //httpResponse, SchemeType, } from "../../../service/http-kernel"; import HttpError from "../../errors/httpError"; import Context, { - contextRequest, - contextResponse, + //contextRequest, + //contextResponse, HTTPMethod, } from "../Context"; import { extend, Container, - Service, - Severity, - Msgid, - Message, - Pdu, - KernelEventsType, + //Service, + //Severity, + //Msgid, + //Message, + //Pdu, + //KernelEventsType, } from "nodefony"; import HttpRequest from "./Request"; import HttpResponse from "./Response"; @@ -360,6 +360,10 @@ class HttpContext extends Context { this.response.setContentType("json", "utf-8"); } } + override setContextJson(encoding: BufferEncoding = "utf-8"): void { + this.isJson = true; + this.response.setContentType("json", encoding); + } } export default HttpContext; diff --git a/src/packages/@nodefony/http/nodefony/src/context/http/Request.ts b/src/packages/@nodefony/http/nodefony/src/context/http/Request.ts index 5807ddc..9d80163 100644 --- a/src/packages/@nodefony/http/nodefony/src/context/http/Request.ts +++ b/src/packages/@nodefony/http/nodefony/src/context/http/Request.ts @@ -4,9 +4,9 @@ import HttpContext from "../http/HttpContext"; import url, { URL } from "node:url"; import { HTTPMethod, Cookies } from "../Context"; import QS from "qs"; -import Http2Resquest from "../http2/Request"; +import Http2Request from "../http2/Request"; import formidable, { IncomingForm } from "formidable"; -import { Container } from "nodefony"; +//import { Container } from "nodefony"; import { ParserXml, ParserQs, Parser, acceptParser } from "./parser"; import nodefony, { extend, Pdu, Message, Severity, Msgid } from "nodefony"; import Session from "../../session/session"; @@ -46,7 +46,7 @@ type ParserType = | Parser | InstanceType; -class HttpResquest { +class HttpRequest { context: HttpContext; request: http.IncomingMessage | http2.Http2ServerRequest; url: URL; @@ -438,4 +438,4 @@ class HttpResquest { } } -export default HttpResquest; +export default HttpRequest; diff --git a/src/packages/@nodefony/http/nodefony/src/context/http/parser.ts b/src/packages/@nodefony/http/nodefony/src/context/http/parser.ts index f794d7f..5f40f7f 100644 --- a/src/packages/@nodefony/http/nodefony/src/context/http/parser.ts +++ b/src/packages/@nodefony/http/nodefony/src/context/http/parser.ts @@ -1,13 +1,13 @@ -import HttpResquest from "./Request"; -import Http2Resquest from "../http2/Request"; +import HttpRequest from "./Request"; +import Http2Request from "../http2/Request"; import QS from "qs"; import { extend } from "nodefony"; import xml2js from "xml2js"; class Parser { - request: HttpResquest | Http2Resquest; + request: HttpRequest | Http2Request; chunks: Buffer[]; - constructor(request: HttpResquest | Http2Resquest) { + constructor(request: HttpRequest | Http2Request) { this.request = request; this.chunks = []; this.request.request.on("data", (data) => { @@ -33,7 +33,7 @@ class Parser { class ParserQs extends Parser { parserOptions: QS.IParseOptions; charset: BufferEncoding = "utf8"; - constructor(request: HttpResquest | Http2Resquest) { + constructor(request: HttpRequest | Http2Request) { super(request); this.parserOptions = this.request.queryStringOptions || {}; } @@ -62,7 +62,7 @@ class ParserXml extends Parser { xmlParser: xml2js.Parser; charset: BufferEncoding = "utf8"; constructor( - request: HttpResquest | Http2Resquest, + request: HttpRequest | Http2Request, settingsXml?: xml2js.ParserOptions ) { super(request); diff --git a/src/packages/@nodefony/http/nodefony/src/context/http2/Request.ts b/src/packages/@nodefony/http/nodefony/src/context/http2/Request.ts index 60c968a..0001408 100644 --- a/src/packages/@nodefony/http/nodefony/src/context/http2/Request.ts +++ b/src/packages/@nodefony/http/nodefony/src/context/http2/Request.ts @@ -1,9 +1,9 @@ import http2 from "node:http2"; import HttpContext from "../http/HttpContext"; -import HttpResquest from "../http/Request"; +import HttpRequest from "../http/Request"; import { HTTPMethod } from "../Context"; -class Http2Resquest extends HttpResquest { +class Http2Request extends HttpRequest { context: HttpContext; override request: http2.Http2ServerRequest; constructor(request: http2.Http2ServerRequest, context: HttpContext) { @@ -37,4 +37,4 @@ class Http2Resquest extends HttpResquest { } } -export default Http2Resquest; +export default Http2Request; diff --git a/src/packages/@nodefony/http/nodefony/src/context/websocket/Response.ts b/src/packages/@nodefony/http/nodefony/src/context/websocket/Response.ts index 422dfcd..97860a1 100644 --- a/src/packages/@nodefony/http/nodefony/src/context/websocket/Response.ts +++ b/src/packages/@nodefony/http/nodefony/src/context/websocket/Response.ts @@ -1,11 +1,29 @@ import Cookie from "../../cookies/cookie"; class WebsocketResponse { statusCode: number = 1000; + body: Buffer | null = null; + encoding: BufferEncoding = "utf-8"; constructor() {} addCookie(cookie: Cookie) {} setCookie(cookie: Cookie) {} + + setBody( + ele: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding | undefined + ) { + if (typeof ele === "string") { + this.body = Buffer.from(ele, encoding || this.encoding); + } else if (ele instanceof ArrayBuffer || ele instanceof SharedArrayBuffer) { + this.body = Buffer.from(ele); + } else if ("buffer" in ele && ele.buffer instanceof ArrayBuffer) { + this.body = Buffer.from(ele.buffer); + } + return this.body; + } + setHeaders() {} + setStatusCode() {} } export default WebsocketResponse; diff --git a/src/packages/@nodefony/http/nodefony/src/context/websocket/WebsocketContext.ts b/src/packages/@nodefony/http/nodefony/src/context/websocket/WebsocketContext.ts index 4c26d2a..098d6a5 100644 --- a/src/packages/@nodefony/http/nodefony/src/context/websocket/WebsocketContext.ts +++ b/src/packages/@nodefony/http/nodefony/src/context/websocket/WebsocketContext.ts @@ -30,6 +30,7 @@ class WebsocketContext extends Context { response: websocketResponse; cookies: Cookies = {}; acceptedProtocol?: string; + isJson: boolean = true; constructor( container: Container, request: websocket.request, @@ -46,6 +47,8 @@ class WebsocketContext extends Context { async handle(): Promise {} + //override async send(chunk?: any, encoding?: BufferEncoding) {} + getRemoteAddress(): string | null { return this.request?.remoteAddress; } @@ -57,6 +60,10 @@ class WebsocketContext extends Context { getUserAgent(): string { return ""; } + + override setContextJson(encoding: BufferEncoding = "utf-8"): void { + this.isJson = true; + } } export default WebsocketContext; diff --git a/src/packages/@nodefony/http/nodefony/src/session/session.ts b/src/packages/@nodefony/http/nodefony/src/session/session.ts index 27f60b8..faadede 100644 --- a/src/packages/@nodefony/http/nodefony/src/session/session.ts +++ b/src/packages/@nodefony/http/nodefony/src/session/session.ts @@ -25,7 +25,7 @@ import { import Cookie, { CookieOptionsType } from "../cookies/cookie"; import HttpContext from "../context/http/HttpContext"; import WebsocketContext from "../context/websocket/WebsocketContext"; -import HttpResquest from "../context/http/Request"; +import HttpRequest from "../context/http/Request"; type algorithmSessionType = { algorithm: string; @@ -331,7 +331,7 @@ class Session extends Container { this.applyTranId = false; } if (!this.options.use_only_cookies && !this.id) { - const request = this.context?.request as HttpResquest; + const request = this.context?.request as HttpRequest; if (request && this.name in request.query) { this.id = this.getId(request.query[this.name]); } diff --git a/src/packages/@nodefony/http/nodefony/types/index.d.ts b/src/packages/@nodefony/http/nodefony/types/index.d.ts index c88bd6c..38511f0 100644 --- a/src/packages/@nodefony/http/nodefony/types/index.d.ts +++ b/src/packages/@nodefony/http/nodefony/types/index.d.ts @@ -5,8 +5,26 @@ import HttpKernel from "../service/http-kernel"; import HttpError from "../src/errors/httpError"; import WebsocketContext from "../src/context/websocket/WebsocketContext"; import HttpContext from "../src/context/http/HttpContext"; +import Http2Request from "../src/context/http2/Request"; +import HttpRequest from "../src/context/http/Request"; +import Session from "../src/session/session"; +import SessionsService from "../service/sessions/sessions-service"; export default Http; -export { Context, HttpKernel, HttpError, WebsocketContext, HttpContext }; +export { + Context, + HttpKernel, + HttpError, + WebsocketContext, + HttpContext, + Http2Request, + HttpRequest, + Session, + SessionsService, +}; export * from "../service/http-kernel"; export * from "../src/context/Context"; +// export * from "../src/context/http/Request"; +// export * from "../src/context/http/Response"; +// export * from "../src/context/http2/Request"; +// export * from "../src/context/http2/Response";