@nano-app/backend 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.d.ts CHANGED
@@ -1,13 +1,9 @@
1
- import { Endpoint } from "@all";
2
- type NanoAppConfig = {
3
- port?: number;
4
- endpoints: Endpoint[];
5
- };
1
+ import { type NanoAppConfig } from "./index";
6
2
  export declare class NanoApp {
7
3
  private app;
8
4
  private router;
9
5
  private config;
10
6
  constructor(config: NanoAppConfig);
7
+ getApp(): import("express-serve-static-core").Express;
11
8
  start(listener?: () => void): Promise<void>;
12
9
  }
13
- export {};
package/dist/app.js CHANGED
@@ -5,31 +5,83 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.NanoApp = void 0;
7
7
  const express_1 = __importDefault(require("express"));
8
- const dotenv_1 = __importDefault(require("dotenv"));
9
- const _all_1 = require("@all");
10
- dotenv_1.default.config();
8
+ const cors_1 = __importDefault(require("cors"));
9
+ const helmet_1 = __importDefault(require("helmet"));
10
+ const compression_1 = __importDefault(require("compression"));
11
+ const morgan_1 = __importDefault(require("morgan"));
12
+ const express_rate_limit_1 = __importDefault(require("express-rate-limit"));
13
+ const index_1 = require("./index");
11
14
  class NanoApp {
12
15
  app = (0, express_1.default)();
13
16
  router;
14
17
  config = {
15
- port: 3000,
16
18
  endpoints: [],
19
+ enableEntities: true,
20
+ port: 3000,
21
+ rateLimit: {
22
+ windowMs: 15 * 60 * 1000, // 15 minutos
23
+ max: 1000, // Máximo 1000 peticiones por IP
24
+ message: 'Too many requests, please try again later.'
25
+ },
26
+ morgan: {
27
+ tokens: {},
28
+ format: 'combined',
29
+ },
30
+ expressConfig: {
31
+ limit: '10kb',
32
+ },
17
33
  };
18
34
  constructor(config) {
19
- // Inicializar el router
20
- this.router = new _all_1.Router(config.endpoints);
21
35
  // Inicializar la configuración
22
36
  this.config = {
23
37
  ...this.config,
24
38
  ...config,
25
39
  };
40
+ // Inicializar el router
41
+ this.router = new index_1.Router(this.config.endpoints.concat(this.config.enableEntities ? [new index_1.Entities('/:endpoint{/:id}')] : []));
42
+ // Inicializar setters
43
+ if (this.config.setters) {
44
+ Object.entries(this.config.setters).forEach(([key, value]) => {
45
+ this.app.set(key, value);
46
+ });
47
+ }
48
+ // Inicializar morgan
49
+ Object.entries(this.config.morgan?.tokens || {}).forEach(([key, value]) => {
50
+ morgan_1.default.token(key, value);
51
+ });
52
+ this.app.use((0, morgan_1.default)(this.config.morgan?.format ?? 'combined'));
53
+ // Inicializar seguridad y optimizacion
54
+ this.app.use((0, cors_1.default)());
55
+ this.app.use((0, helmet_1.default)());
56
+ this.app.use((0, compression_1.default)());
57
+ // Inicializar proteccion contra ataques
58
+ this.app.use((0, express_rate_limit_1.default)(this.config.rateLimit));
59
+ // Inicializar limite de tamaño del body
60
+ this.app.use(express_1.default.json(this.config.expressConfig));
26
61
  }
62
+ getApp() { return this.app; }
27
63
  async start(listener) {
28
- this.app.use(express_1.default.json());
64
+ // Middlewares
65
+ (this.config.middlewares || []).forEach(middleware => this.app.use(middleware));
29
66
  // Registrar las rutas
30
67
  this.app.use('/', this.router.getRoutes());
68
+ // Middleware de error (debe ir al final)
69
+ if (this.config.errorMiddleware) {
70
+ this.app.use(this.config.errorMiddleware);
71
+ }
72
+ else {
73
+ this.app.use((err, _, res, __) => {
74
+ res.status(err.status || 500).json({
75
+ success: false,
76
+ message: err.message || 'Error interno del servidor'
77
+ });
78
+ });
79
+ }
31
80
  // Iniciar el servidor
32
- this.app.listen(Number(this.config.port), listener || (() => console.log(`Servidor corriendo en el puerto ${this.config.port}`)));
81
+ this.app.listen(Number(this.config.port), () => {
82
+ console.log(`Server running on port ${this.config.port}`);
83
+ listener?.(); // Ejecutar el listener si se proporciona
84
+ });
33
85
  }
34
86
  }
35
87
  exports.NanoApp = NanoApp;
@@ -1,9 +1,10 @@
1
- import { ApiResponse } from "@nano-app/core";
2
1
  import { Request, Response } from "express";
2
+ import { PrismaClient, type ApiResponse } from "../index";
3
3
  export declare abstract class Endpoint<BeforeResult = any> {
4
+ protected prismaClient: PrismaClient;
4
5
  private methodMap;
5
- endpointName: string;
6
- constructor(endpointName?: string);
6
+ path: string;
7
+ constructor(path?: string);
7
8
  /** Metodos envoltorios */
8
9
  protected BEFORE(_req: Request): Promise<BeforeResult>;
9
10
  protected AFTER(_result: ApiResponse): Promise<ApiResponse>;
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Endpoint = void 0;
4
+ const index_1 = require("../index");
4
5
  class Endpoint {
5
- // protected prismaClient = new PrismaClient();
6
+ prismaClient = new index_1.PrismaClient();
6
7
  methodMap = {};
7
- endpointName = '';
8
- constructor(endpointName) {
9
- this.endpointName = endpointName || 'default';
8
+ path = '';
9
+ constructor(path) {
10
+ this.path = path || 'default';
10
11
  this.methodMap = {
11
12
  'GET': this.GET.bind(this),
12
13
  'POST': this.POST.bind(this),
@@ -26,16 +27,16 @@ class Endpoint {
26
27
  * Si no se implementan, se lanza un error por defecto
27
28
  */
28
29
  async GET(_req, _res, _beforeParams) {
29
- throw { message: `Método GET no implementado para ${this.endpointName}` };
30
+ throw { message: `Método GET no implementado para ${this.path}` };
30
31
  }
31
32
  async POST(_req, _res, _beforeParams) {
32
- throw { message: `Método POST no implementado para ${this.endpointName}` };
33
+ throw { message: `Método POST no implementado para ${this.path}` };
33
34
  }
34
35
  async PUT(_req, _res, _beforeParams) {
35
- throw { message: `Método PUT no implementado para ${this.endpointName}` };
36
+ throw { message: `Método PUT no implementado para ${this.path}` };
36
37
  }
37
38
  async DELETE(_req, _res, _beforeParams) {
38
- throw { message: `Método DELETE no implementado para ${this.endpointName}` };
39
+ throw { message: `Método DELETE no implementado para ${this.path}` };
39
40
  }
40
41
  /**
41
42
  * Ejecuta la lógica específica del endpoint
@@ -50,7 +51,10 @@ class Endpoint {
50
51
  this.BEFORE(req)
51
52
  .then((beforeParams) => handler(req, res, beforeParams))
52
53
  .then(result => this.AFTER(result))
53
- .then(result => res.json(result));
54
+ .then(result => res.json({
55
+ success: true,
56
+ ...result
57
+ }));
54
58
  }
55
59
  catch (error) {
56
60
  res.status(500).json({
@@ -1,4 +1,4 @@
1
- import { Endpoint } from '@all';
1
+ import { Endpoint } from './Endpoint';
2
2
  export declare class Router {
3
3
  private router;
4
4
  constructor(endpoints: Endpoint[]);
@@ -9,8 +9,10 @@ class Router {
9
9
  router = express_1.default.Router();
10
10
  constructor(endpoints) {
11
11
  // Registrar todos los endpoints
12
+ console.log(`Endpoints registered:`);
12
13
  endpoints.forEach(endpoint => {
13
- this.router.all(`${endpoint.endpointName}`, endpoint.execute.bind(endpoint));
14
+ console.log(` - ${endpoint.path}`);
15
+ this.router.all(`${endpoint.path}`, endpoint.execute.bind(endpoint));
14
16
  });
15
17
  }
16
18
  getRoutes() {
package/dist/index.d.ts CHANGED
@@ -1,3 +1,10 @@
1
1
  export * from "./http/Endpoint";
2
2
  export * from "./http/Router";
3
+ export * from "./odata/Entities";
4
+ export * from "./odata/QueryBuilder";
5
+ export * from "./prisma/Client";
6
+ export * from "./types/api";
7
+ export * from "./types/app";
8
+ export * from "./types/odata";
9
+ export * from "./utils/Formatter";
3
10
  export * from "./app";
package/dist/index.js CHANGED
@@ -16,4 +16,11 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./http/Endpoint"), exports);
18
18
  __exportStar(require("./http/Router"), exports);
19
+ __exportStar(require("./odata/Entities"), exports);
20
+ __exportStar(require("./odata/QueryBuilder"), exports);
21
+ __exportStar(require("./prisma/Client"), exports);
22
+ __exportStar(require("./types/api"), exports);
23
+ __exportStar(require("./types/app"), exports);
24
+ __exportStar(require("./types/odata"), exports);
25
+ __exportStar(require("./utils/Formatter"), exports);
19
26
  __exportStar(require("./app"), exports);
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@nano-app/backend",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Backend for nano-app architecture",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "files": [
8
- "dist",
9
- "bin"
8
+ "*.js",
9
+ "*.d.ts",
10
+ "http"
10
11
  ],
11
12
  "scripts": {
12
- "dev": "tsx watch src/test.ts",
13
13
  "build": "tsc",
14
14
  "prepublishOnly": "npm run build"
15
15
  },
@@ -22,16 +22,23 @@
22
22
  "author": "Cristian Serrano",
23
23
  "license": "MIT",
24
24
  "dependencies": {
25
- "@nano-app/core": "^0.1.0",
26
25
  "@prisma/adapter-pg": "^7.4.0",
27
26
  "@prisma/client": "^7.4.0",
28
- "express": "^5.2.1"
27
+ "compression": "^1.8.1",
28
+ "cors": "^2.8.5",
29
+ "dotenv": "^17.2.3",
30
+ "express": "^5.2.1",
31
+ "express-rate-limit": "^8.2.1",
32
+ "helmet": "^8.1.0",
33
+ "morgan": "^1.10.1"
29
34
  },
30
35
  "devDependencies": {
31
- "@types/dotenv": "^8.2.3",
36
+ "@types/compression": "^1.8.1",
37
+ "@types/cors": "^2.8.19",
32
38
  "@types/express": "^5.0.0",
39
+ "@types/morgan": "^1.9.10",
33
40
  "@types/node": "^20.0.0",
34
- "typescript": "^5.3.0",
35
- "tsx": "^4.7.0"
41
+ "tsx": "^4.7.0",
42
+ "typescript": "^5.3.0"
36
43
  }
37
44
  }
package/dist/test.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/dist/test.js DELETED
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const _all_1 = require("@all");
4
- class HealthEndpoint extends _all_1.Endpoint {
5
- async GET(_ctx) {
6
- return { success: true, message: "Health!" };
7
- }
8
- }
9
- const app = new _all_1.NanoApp({
10
- endpoints: [
11
- new HealthEndpoint("/service/health"),
12
- new HealthEndpoint("/:entity{/:id}"),
13
- ]
14
- });
15
- app.start();