@avleon/core 0.0.4

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.
Files changed (44) hide show
  1. package/README.md +1 -0
  2. package/dist/config.d.ts +30 -0
  3. package/dist/config.js +19 -0
  4. package/dist/container.d.ts +19 -0
  5. package/dist/container.js +51 -0
  6. package/dist/controller.d.ts +47 -0
  7. package/dist/controller.js +38 -0
  8. package/dist/decorators.d.ts +8 -0
  9. package/dist/decorators.js +25 -0
  10. package/dist/exceptions/http-exceptions.d.ts +21 -0
  11. package/dist/exceptions/http-exceptions.js +38 -0
  12. package/dist/exceptions/index.d.ts +1 -0
  13. package/dist/exceptions/index.js +17 -0
  14. package/dist/exceptions/system-exception.d.ts +13 -0
  15. package/dist/exceptions/system-exception.js +18 -0
  16. package/dist/helpers.d.ts +24 -0
  17. package/dist/helpers.js +192 -0
  18. package/dist/icore.d.ts +58 -0
  19. package/dist/icore.js +239 -0
  20. package/dist/index.d.ts +10 -0
  21. package/dist/index.js +33 -0
  22. package/dist/map-types.d.ts +12 -0
  23. package/dist/map-types.js +85 -0
  24. package/dist/openapi.d.ts +333 -0
  25. package/dist/openapi.js +27 -0
  26. package/dist/params.d.ts +16 -0
  27. package/dist/params.js +48 -0
  28. package/dist/queue.d.ts +0 -0
  29. package/dist/queue.js +1 -0
  30. package/dist/repository.d.ts +0 -0
  31. package/dist/repository.js +1 -0
  32. package/dist/response.d.ts +9 -0
  33. package/dist/response.js +36 -0
  34. package/dist/results.d.ts +20 -0
  35. package/dist/results.js +32 -0
  36. package/dist/route-methods.d.ts +56 -0
  37. package/dist/route-methods.js +83 -0
  38. package/dist/swagger-schema.d.ts +1 -0
  39. package/dist/swagger-schema.js +29 -0
  40. package/dist/validator-extend.d.ts +1 -0
  41. package/dist/validator-extend.js +22 -0
  42. package/jest.config.ts +9 -0
  43. package/package.json +39 -0
  44. package/tsconfig.json +25 -0
package/dist/icore.js ADDED
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.AppBuilder = void 0;
40
+ const fastify_1 = __importDefault(require("fastify"));
41
+ const typedi_1 = __importDefault(require("typedi"));
42
+ const promises_1 = __importDefault(require("fs/promises")); // Use promises for asynchronous file operations
43
+ const path_1 = __importDefault(require("path"));
44
+ const container_1 = __importStar(require("./container"));
45
+ const helpers_1 = require("./helpers");
46
+ const system_exception_1 = require("./exceptions/system-exception");
47
+ const isTsNode = process.env.TS_NODE_DEV || process.env.TS_NODE_PROJECT || process[Symbol.for("ts-node.register.instance")];
48
+ const controllerDir = path_1.default.join(process.cwd(), isTsNode ? "./src/controllers" : "./dist/cotrollers");
49
+ class _InternalApplication {
50
+ constructor() {
51
+ this.routeSet = new Set(); // Use Set for fast duplicate detection
52
+ this.alreadyRun = false;
53
+ this.routes = new Map();
54
+ this.app = (0, fastify_1.default)();
55
+ }
56
+ static getInternalApp(buildOptions) {
57
+ if (!_InternalApplication.instance) {
58
+ _InternalApplication.instance = new _InternalApplication();
59
+ }
60
+ _InternalApplication.buildOptions = buildOptions;
61
+ return _InternalApplication.instance;
62
+ }
63
+ async buildController(controller) {
64
+ const ctrl = typedi_1.default.get(controller);
65
+ const controllerMeta = Reflect.getMetadata(container_1.CONTROLLER_META_KEY, ctrl.constructor);
66
+ if (!controllerMeta)
67
+ return;
68
+ const prototype = Object.getPrototypeOf(ctrl);
69
+ const methods = Object.getOwnPropertyNames(prototype).filter((name) => name !== "constructor");
70
+ for (const method of methods) {
71
+ const methodMeta = Reflect.getMetadata(container_1.ROUTE_META_KEY, prototype, method);
72
+ if (!methodMeta)
73
+ continue;
74
+ const methodmetaOptions = { method: methodMeta.method.toLowerCase(), path: (0, helpers_1.formatUrl)(controllerMeta.path + methodMeta.path) };
75
+ const routeKey = `${methodmetaOptions.method}:${methodmetaOptions.path}`;
76
+ if (this.routeSet.has(routeKey)) {
77
+ throw new system_exception_1.SystemUseError(`Duplicate Error: Duplicate route found for methoed ${methodMeta.method}: ${methodMeta.path} in ${controller.name}`);
78
+ }
79
+ this.routeSet.add(routeKey);
80
+ const allMeta = this._processMeta(prototype, controllerMeta, method, methodMeta);
81
+ this.app.route({
82
+ url: methodmetaOptions.path == "" ? "/" : methodmetaOptions.path,
83
+ method: methodmetaOptions.method.toUpperCase(),
84
+ preHandler: async (req, res, next) => {
85
+ for (let bodyMeta of allMeta.body) {
86
+ const args = await this._mapArgs(req, allMeta);
87
+ if (bodyMeta.validatorClass) {
88
+ const err = await (0, helpers_1.validateObjectByInstance)(bodyMeta.dataType, args[bodyMeta.index]);
89
+ if (err) {
90
+ console.log("Has validation error", err);
91
+ return await res.code(400).send({
92
+ code: 400,
93
+ errorType: "ValidationError",
94
+ errors: err,
95
+ message: err.message
96
+ });
97
+ }
98
+ }
99
+ }
100
+ next();
101
+ },
102
+ handler: async (req, res) => {
103
+ const args = await this._mapArgs(req, allMeta);
104
+ try {
105
+ return await prototype[method].apply(ctrl, args);
106
+ }
107
+ catch (err) {
108
+ console.error(err);
109
+ return res.code(err.statusCode || 500).send({
110
+ code: err.statusCode || 500,
111
+ errorType: err.name || "InternalServerError",
112
+ message: err.message,
113
+ });
114
+ }
115
+ },
116
+ });
117
+ }
118
+ }
119
+ async _mapArgs(req, meta) {
120
+ const args = [];
121
+ if (meta.params.length > 0) {
122
+ meta.params.forEach((param) => {
123
+ const value = param.key === "all" ? req.params : req.params[param.key];
124
+ args[param.index] = value;
125
+ });
126
+ }
127
+ if (meta.query.length > 0) {
128
+ meta.query.forEach((q) => {
129
+ const value = q.key === "all" ? req.query : req === null || req === void 0 ? void 0 : req.query[q.key];
130
+ args[q.index] = value;
131
+ });
132
+ }
133
+ if (meta.body.length > 0) {
134
+ meta.body.forEach(async (body) => {
135
+ args[body.index] = req.body;
136
+ });
137
+ }
138
+ if (meta.headers.length > 0) {
139
+ meta.headers.forEach((header) => {
140
+ const value = header.key === "all" ? req.headers : req.headers[header.key];
141
+ args[header.index] = value;
142
+ });
143
+ }
144
+ return args;
145
+ }
146
+ _processMeta(prototype, controllerMeta, method, methodMeta) {
147
+ const paramsMetaList = Reflect.getMetadata(container_1.PARAM_META_KEY, prototype, method) || [];
148
+ const queryMetaList = Reflect.getMetadata(container_1.QUERY_META_KEY, prototype, method) || [];
149
+ const bodyMetaList = Reflect.getMetadata(container_1.REQUEST_BODY_META_KEY, prototype, method) || [];
150
+ const headerMetaList = Reflect.getMetadata(container_1.REQUEST_HEADER_META_KEY, prototype, method) || [];
151
+ return { params: paramsMetaList, query: queryMetaList, body: bodyMetaList, headers: headerMetaList };
152
+ }
153
+ async mapControllers() {
154
+ // const controllers = getRegisteredControllers();
155
+ // await Promise.all(controllers.map((controller) => this.buildController(controller)));
156
+ await this._mapControllers();
157
+ }
158
+ async mapGroup(path) {
159
+ }
160
+ async handleRoute(args) {
161
+ console.log(args);
162
+ }
163
+ async mapGet(path = '', fn) {
164
+ this.app.get(path, async (req, res) => {
165
+ const result = await fn.apply(this, [req, res]);
166
+ return res.send(result);
167
+ });
168
+ /* this.handleRoute = fn.apply(this, arguments);
169
+
170
+ this.routes.set(path, async (...args: any[]) => {
171
+ try {
172
+ const result = await fn(...args);
173
+ return result;
174
+ } catch (error) {
175
+ console.error(`Error handling route ${path}:`, error);
176
+ throw error;
177
+ }
178
+ }); */
179
+ }
180
+ async mapPost() { }
181
+ async mapPut() { }
182
+ async mapDelete() { }
183
+ async _mapControllers() {
184
+ const controllers = (0, container_1.getRegisteredControllers)();
185
+ await Promise.all(controllers.map((controller) => this.buildController(controller)));
186
+ }
187
+ async run(port = 4000) {
188
+ if (this.alreadyRun)
189
+ throw new system_exception_1.SystemUseError("App already running");
190
+ this.alreadyRun = true;
191
+ if (_InternalApplication.buildOptions.database) {
192
+ }
193
+ ///await this._mapControllers();
194
+ await this.app.listen({ port });
195
+ console.log(`Application running on port: ${port}`);
196
+ }
197
+ }
198
+ _InternalApplication.buildOptions = {};
199
+ class AppBuilder {
200
+ constructor() {
201
+ this.alreadyBuilt = false;
202
+ this.databse = false;
203
+ }
204
+ static createBuilder() {
205
+ if (!AppBuilder.instance) {
206
+ AppBuilder.instance = new AppBuilder();
207
+ }
208
+ return AppBuilder.instance;
209
+ }
210
+ async registerPlugin(plugin, options) {
211
+ container_1.default.set(plugin, plugin.prototype);
212
+ }
213
+ async useDatabase() {
214
+ this.databse = true;
215
+ }
216
+ async build() {
217
+ //console.log("Hello", hello())
218
+ if (this.alreadyBuilt)
219
+ throw new Error("Already built");
220
+ this.alreadyBuilt = true;
221
+ const controllers = [];
222
+ const files = await promises_1.default.readdir(controllerDir);
223
+ for (const file of files) {
224
+ if (isTsNode ? file.endsWith(".ts") : file.endsWith(".js")) {
225
+ const filePath = path_1.default.join(controllerDir, file);
226
+ const module = await Promise.resolve(`${filePath}`).then(s => __importStar(require(s)));
227
+ for (const exported of Object.values(module)) {
228
+ if (typeof exported === "function" && (0, container_1.isApiController)(exported)) {
229
+ controllers.push(exported);
230
+ }
231
+ }
232
+ }
233
+ }
234
+ const app = _InternalApplication.getInternalApp({ database: this.databse });
235
+ controllers.forEach(container_1.registerController);
236
+ return app;
237
+ }
238
+ }
239
+ exports.AppBuilder = AppBuilder;
@@ -0,0 +1,10 @@
1
+ export * from './icore';
2
+ export { inject } from './helpers';
3
+ export * from "./decorators";
4
+ export * from "./config";
5
+ export * from "./openapi";
6
+ export * from "./map-types";
7
+ export * from './response';
8
+ export * from './exceptions';
9
+ export * from './validator-extend';
10
+ export { default as Container } from './container';
package/dist/index.js ADDED
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.Container = exports.inject = void 0;
21
+ //export * from "./iqra-core";
22
+ __exportStar(require("./icore"), exports);
23
+ var helpers_1 = require("./helpers");
24
+ Object.defineProperty(exports, "inject", { enumerable: true, get: function () { return helpers_1.inject; } });
25
+ __exportStar(require("./decorators"), exports);
26
+ __exportStar(require("./config"), exports);
27
+ __exportStar(require("./openapi"), exports);
28
+ __exportStar(require("./map-types"), exports);
29
+ __exportStar(require("./response"), exports);
30
+ __exportStar(require("./exceptions"), exports);
31
+ __exportStar(require("./validator-extend"), exports);
32
+ var container_1 = require("./container");
33
+ Object.defineProperty(exports, "Container", { enumerable: true, get: function () { return __importDefault(container_1).default; } });
@@ -0,0 +1,12 @@
1
+ import "reflect-metadata";
2
+ type Constructor<T = any> = new (...args: any[]) => T;
3
+ export declare function PartialType<T>(BaseClass: Constructor<T>): Constructor<Partial<T>>;
4
+ /**
5
+ * Utility to pick specific properties from a class.
6
+ */
7
+ export declare function PickType<T, K extends keyof T>(BaseClass: Constructor<T>, keys: K[]): Constructor<Pick<T, K>>;
8
+ /**
9
+ * Utility to omit specific properties from a class.
10
+ */
11
+ export declare function OmitType<T, K extends keyof T>(BaseClass: Constructor<T>, keys: K[]): Constructor<Omit<T, K>>;
12
+ export {};
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PartialType = PartialType;
4
+ exports.PickType = PickType;
5
+ exports.OmitType = OmitType;
6
+ require("reflect-metadata");
7
+ function PartialType(BaseClass) {
8
+ const baseProperties = [];
9
+ let currentPrototype = BaseClass.prototype;
10
+ // Collect properties from the base class (including inherited ones)
11
+ while (currentPrototype && currentPrototype !== Object.prototype) {
12
+ const properties = Object.getOwnPropertyNames(currentPrototype).filter((prop) => prop !== "constructor");
13
+ // Retrieve metadata for each property
14
+ properties.forEach((key) => {
15
+ // Check if the property has type metadata (design:type)
16
+ const designType = Reflect.getMetadata("design:type", currentPrototype, key);
17
+ if (designType) {
18
+ baseProperties.push(key);
19
+ }
20
+ // Retrieve validation metadata (class-validator)
21
+ const validationMetadata = Reflect.getMetadataKeys(currentPrototype, key);
22
+ validationMetadata.forEach((metadataKey) => {
23
+ });
24
+ });
25
+ currentPrototype = Object.getPrototypeOf(currentPrototype); // Move up the prototype chain
26
+ }
27
+ class PartialClass {
28
+ }
29
+ // Define properties as optional and copy metadata
30
+ baseProperties.forEach((key) => {
31
+ const propertyType = Reflect.getMetadata("design:type", BaseClass.prototype, key);
32
+ Reflect.defineMetadata("design:type", propertyType, PartialClass.prototype, key);
33
+ // Propagate class-validator metadata to the new class
34
+ const validationMetadataKeys = Reflect.getMetadataKeys(BaseClass.prototype, key) || [];
35
+ validationMetadataKeys.forEach((metadataKey) => {
36
+ const metadataValue = Reflect.getMetadata(metadataKey, BaseClass.prototype, key);
37
+ Reflect.defineMetadata(metadataKey, metadataValue, PartialClass.prototype, key);
38
+ });
39
+ });
40
+ // Copy other metadata from the base class (non-property metadata)
41
+ Reflect.getMetadataKeys(BaseClass.prototype).forEach((key) => {
42
+ const metadataValue = Reflect.getMetadata(key, BaseClass.prototype);
43
+ Reflect.defineMetadata(key, metadataValue, PartialClass.prototype);
44
+ });
45
+ return PartialClass;
46
+ }
47
+ /**
48
+ * Utility to pick specific properties from a class.
49
+ */
50
+ function PickType(BaseClass, keys) {
51
+ class PickClass {
52
+ constructor() {
53
+ keys.forEach((key) => {
54
+ Reflect.defineMetadata("design:type", Reflect.getMetadata("design:type", BaseClass.prototype, key), this, key);
55
+ });
56
+ }
57
+ }
58
+ Reflect.decorate([Reflect.metadata("design:properties", keys)], PickClass);
59
+ // Copy metadata from BaseClass to PickClass
60
+ Reflect.getMetadataKeys(BaseClass.prototype).forEach((key) => {
61
+ Reflect.defineMetadata(key, Reflect.getMetadata(key, BaseClass.prototype), PickClass.prototype);
62
+ });
63
+ return PickClass;
64
+ }
65
+ /**
66
+ * Utility to omit specific properties from a class.
67
+ */
68
+ function OmitType(BaseClass, keys) {
69
+ const allKeys = Reflect.getMetadata("design:properties", BaseClass) || [];
70
+ const omitKeys = new Set(keys);
71
+ const finalKeys = allKeys.filter((key) => !omitKeys.has(key));
72
+ class OmitClass {
73
+ constructor() {
74
+ finalKeys.forEach((key) => {
75
+ Reflect.defineMetadata("design:type", Reflect.getMetadata("design:type", BaseClass.prototype, key), this, key);
76
+ });
77
+ }
78
+ }
79
+ Reflect.decorate([Reflect.metadata("design:properties", finalKeys)], OmitClass);
80
+ // Copy metadata from BaseClass to OmitClass
81
+ Reflect.getMetadataKeys(BaseClass.prototype).forEach((key) => {
82
+ Reflect.defineMetadata(key, Reflect.getMetadata(key, BaseClass.prototype), OmitClass.prototype);
83
+ });
84
+ return OmitClass;
85
+ }