@webtypen/webframez-core 0.0.2 → 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.
@@ -14,6 +14,7 @@ jobs:
14
14
  node-version: 18
15
15
  registry-url: https://npm.pkg.github.com/
16
16
  - run: npm install
17
+ - run: npm run build
17
18
  - run: npm publish
18
19
  env:
19
20
  NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
@@ -26,6 +27,7 @@ jobs:
26
27
  node-version: 18
27
28
  registry-url: https://registry.npmjs.org/
28
29
  - run: npm install
30
+ - run: npm run build
29
31
  - run: npm publish --access public
30
32
  env:
31
33
  NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
@@ -0,0 +1,10 @@
1
+ import { Controller } from "./Controller/Controller";
2
+ export declare class BaseKernel {
3
+ static commands: never[];
4
+ static controller: {
5
+ [key: string]: Controller;
6
+ };
7
+ static middleware: {
8
+ [key: string]: any;
9
+ };
10
+ }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseKernel = void 0;
4
+ class BaseKernel {
5
+ }
6
+ exports.BaseKernel = BaseKernel;
7
+ BaseKernel.commands = [];
8
+ BaseKernel.controller = {};
@@ -0,0 +1,2 @@
1
+ export declare class Controller {
2
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Controller = void 0;
4
+ class Controller {
5
+ }
6
+ exports.Controller = Controller;
@@ -0,0 +1,11 @@
1
+ import { Model } from "./Model";
2
+ import { QueryBuilder } from "./QueryBuilder";
3
+ export declare class BaseDBDriver {
4
+ config?: object;
5
+ setConfig(config: object): void;
6
+ connect(): Promise<void>;
7
+ close(client: any): Promise<void>;
8
+ handleQueryBuilder(client: any, queryBuilder: QueryBuilder): Promise<void>;
9
+ execute(client: any, data: any): Promise<void>;
10
+ onModelSave(model: Model, saveStatus: any | null | undefined): Promise<Model>;
11
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.BaseDBDriver = void 0;
13
+ class BaseDBDriver {
14
+ setConfig(config) {
15
+ this.config = config;
16
+ }
17
+ connect() {
18
+ return __awaiter(this, void 0, void 0, function* () { });
19
+ }
20
+ close(client) {
21
+ return __awaiter(this, void 0, void 0, function* () { });
22
+ }
23
+ handleQueryBuilder(client, queryBuilder) {
24
+ return __awaiter(this, void 0, void 0, function* () { });
25
+ }
26
+ execute(client, data) {
27
+ return __awaiter(this, void 0, void 0, function* () { });
28
+ }
29
+ onModelSave(model, saveStatus) {
30
+ return __awaiter(this, void 0, void 0, function* () {
31
+ return model;
32
+ });
33
+ }
34
+ }
35
+ exports.BaseDBDriver = BaseDBDriver;
@@ -0,0 +1,17 @@
1
+ import { QueryBuilder } from "./QueryBuilder";
2
+ declare class DBConnectionFacade {
3
+ connections: {
4
+ [key: string]: any;
5
+ };
6
+ getConnectionConfig(connection: string): any;
7
+ getConnectionDriver(connection: string): any;
8
+ getConnection(connectionName?: string): Promise<any>;
9
+ runQuery(query: QueryBuilder, options?: {
10
+ [name: string]: any;
11
+ }): Promise<any>;
12
+ execute(data: any, connectionName?: string): Promise<any>;
13
+ getDriver(connectionName?: string): Promise<any>;
14
+ mapDataToModel(model: any, data: any): any;
15
+ }
16
+ export declare const DBConnection: DBConnectionFacade;
17
+ export {};
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.DBConnection = void 0;
16
+ const DBDriver_1 = require("./DBDriver");
17
+ // @ts-ignore
18
+ const database_1 = __importDefault(require("../../../../../config/database"));
19
+ class DBConnectionFacade {
20
+ constructor() {
21
+ this.connections = {};
22
+ }
23
+ getConnectionConfig(connection) {
24
+ if (!connection) {
25
+ connection = database_1.default.defaultConnection;
26
+ }
27
+ if (!connection ||
28
+ !database_1.default ||
29
+ !database_1.default.connections ||
30
+ !database_1.default.connections[connection]) {
31
+ throw new Error("No connection given ...");
32
+ }
33
+ return database_1.default.connections[connection];
34
+ }
35
+ getConnectionDriver(connection) {
36
+ const config = this.getConnectionConfig(connection);
37
+ if (!config || !config["driver"]) {
38
+ return null;
39
+ }
40
+ const driverClass = DBDriver_1.DBDrivers.get(config["driver"]);
41
+ const driver = new driverClass();
42
+ driver.setConfig(config);
43
+ return driver;
44
+ }
45
+ getConnection(connectionName) {
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ if (!connectionName) {
48
+ connectionName = database_1.default.defaultConnection;
49
+ }
50
+ if (!connectionName) {
51
+ return null;
52
+ }
53
+ if (this.connections[connectionName] &&
54
+ this.connections[connectionName].driver) {
55
+ // Use cached connection
56
+ return this.connections[connectionName];
57
+ }
58
+ // Create new connection and cache it
59
+ const driver = this.getConnectionDriver(connectionName);
60
+ const client = yield driver.connect();
61
+ this.connections[connectionName] = {
62
+ driver: driver,
63
+ client: client,
64
+ };
65
+ return this.connections[connectionName];
66
+ });
67
+ }
68
+ runQuery(query, options) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ const connection = yield this.getConnection();
71
+ const data = yield connection.driver.handleQueryBuilder(connection.client, query);
72
+ if (options && options.raw) {
73
+ return data;
74
+ }
75
+ if (!data) {
76
+ return null;
77
+ }
78
+ // @ToDo: Model-Mapping
79
+ return data;
80
+ });
81
+ }
82
+ execute(data, connectionName) {
83
+ return __awaiter(this, void 0, void 0, function* () {
84
+ const connection = yield this.getConnection(connectionName);
85
+ return yield connection.driver.execute(connection.client, data);
86
+ });
87
+ }
88
+ getDriver(connectionName) {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ const connection = yield this.getConnection(connectionName);
91
+ return connection.driver;
92
+ });
93
+ }
94
+ mapDataToModel(model, data) {
95
+ const obj = new model();
96
+ if (data) {
97
+ for (let i in data) {
98
+ obj[i] = data[i];
99
+ }
100
+ }
101
+ return obj;
102
+ }
103
+ }
104
+ exports.DBConnection = new DBConnectionFacade();
@@ -0,0 +1,8 @@
1
+ export declare class DBDriversFacade {
2
+ drivers: {
3
+ [key: string]: any;
4
+ };
5
+ register(name: string, component: any): void;
6
+ get(name: string): any;
7
+ }
8
+ export declare const DBDrivers: DBDriversFacade;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DBDrivers = exports.DBDriversFacade = void 0;
4
+ class DBDriversFacade {
5
+ constructor() {
6
+ this.drivers = {};
7
+ }
8
+ register(name, component) {
9
+ this.drivers[name] = component;
10
+ }
11
+ get(name) {
12
+ return this.drivers[name];
13
+ }
14
+ }
15
+ exports.DBDriversFacade = DBDriversFacade;
16
+ exports.DBDrivers = new DBDriversFacade();
@@ -0,0 +1,44 @@
1
+ import { QueryBuilder } from "./QueryBuilder";
2
+ export declare class Model {
3
+ [key: string]: any | undefined;
4
+ __primaryKey: string;
5
+ __table: string;
6
+ __connection: string | undefined;
7
+ __hidden: string[];
8
+ __unmapped: string[];
9
+ __unmappedSystem: string[];
10
+ /**
11
+ * Creates a new query-builder object and adds a where-clause
12
+ * @param column
13
+ * @param operator
14
+ * @param value
15
+ * @returns QueryBulder
16
+ */
17
+ static where(column: any, operator: any, value: any): QueryBuilder;
18
+ /**
19
+ * Executes a database-aggregation (mostly used by no-sql connections)
20
+ * @param aggregation
21
+ * @returns any
22
+ */
23
+ static aggregate(aggregation: any): Promise<any>;
24
+ /**
25
+ * Returns the model-data without system- and unmapped-fields (new js-object)
26
+ * @returns object
27
+ */
28
+ getModelData(): object;
29
+ /**
30
+ * Returns the model-data without system-, unmapped- and hidden-fields (new js-object)
31
+ * @returns object
32
+ */
33
+ toArray(): object;
34
+ /**
35
+ * Saves the object in the database
36
+ * @returns Model
37
+ */
38
+ save(): Promise<any>;
39
+ /**
40
+ * Deletes the object from the database
41
+ * @returns boolean
42
+ */
43
+ delete(): Promise<boolean>;
44
+ }
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Model = void 0;
13
+ const DBConnection_1 = require("./DBConnection");
14
+ const QueryBuilder_1 = require("./QueryBuilder");
15
+ class Model {
16
+ constructor() {
17
+ this.__primaryKey = "_id";
18
+ this.__table = "";
19
+ this.__connection = undefined;
20
+ this.__hidden = [];
21
+ this.__unmapped = [];
22
+ this.__unmappedSystem = [
23
+ "__primaryKey",
24
+ "__table",
25
+ "__connection",
26
+ "__unmapped",
27
+ "__unmappedSystem",
28
+ "__is_deleted",
29
+ "__hidden",
30
+ ];
31
+ }
32
+ /**
33
+ * Creates a new query-builder object and adds a where-clause
34
+ * @param column
35
+ * @param operator
36
+ * @param value
37
+ * @returns QueryBulder
38
+ */
39
+ static where(column, operator, value) {
40
+ const model = new this();
41
+ const queryBuilder = new QueryBuilder_1.QueryBuilder();
42
+ queryBuilder.setModelMapping(this);
43
+ queryBuilder.table(model.__table);
44
+ queryBuilder.where(column, operator, value);
45
+ return queryBuilder;
46
+ }
47
+ /**
48
+ * Executes a database-aggregation (mostly used by no-sql connections)
49
+ * @param aggregation
50
+ * @returns any
51
+ */
52
+ static aggregate(aggregation) {
53
+ return __awaiter(this, void 0, void 0, function* () {
54
+ const model = new this();
55
+ return yield DBConnection_1.DBConnection.execute({
56
+ type: "aggregation",
57
+ table: model.__table,
58
+ aggregation: aggregation,
59
+ }, model.__connection);
60
+ });
61
+ }
62
+ /**
63
+ * Returns the model-data without system- and unmapped-fields (new js-object)
64
+ * @returns object
65
+ */
66
+ getModelData() {
67
+ const out = {};
68
+ for (let i in this) {
69
+ if (!this.__unmapped.includes(i) && !this.__unmappedSystem.includes(i)) {
70
+ out[i] = this[i];
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+ /**
76
+ * Returns the model-data without system-, unmapped- and hidden-fields (new js-object)
77
+ * @returns object
78
+ */
79
+ toArray() {
80
+ const out = {};
81
+ for (let i in this) {
82
+ if (!this.__unmapped.includes(i) &&
83
+ !this.__unmappedSystem.includes(i) &&
84
+ !this.__hidden.includes(i)) {
85
+ out[i] = this[i];
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+ /**
91
+ * Saves the object in the database
92
+ * @returns Model
93
+ */
94
+ save() {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ let status = null;
97
+ if (this[this.__primaryKey] !== undefined && this[this.__primaryKey]) {
98
+ // Update
99
+ status = yield DBConnection_1.DBConnection.execute({
100
+ type: "updateOne",
101
+ table: this.__table,
102
+ primaryKey: this.__primaryKey,
103
+ filter: { [this.__primaryKey]: this[this.__primaryKey] },
104
+ data: this.getModelData(),
105
+ });
106
+ }
107
+ else {
108
+ // Insert
109
+ status = yield DBConnection_1.DBConnection.execute({
110
+ type: "insertOne",
111
+ table: this.__table,
112
+ data: this.getModelData(),
113
+ });
114
+ }
115
+ // onModelSave
116
+ const driver = yield DBConnection_1.DBConnection.getDriver(this.__connection);
117
+ return driver.onModelSave(this, status);
118
+ });
119
+ }
120
+ /**
121
+ * Deletes the object from the database
122
+ * @returns boolean
123
+ */
124
+ delete() {
125
+ return __awaiter(this, void 0, void 0, function* () {
126
+ if (!this[this.__primaryKey]) {
127
+ return false;
128
+ }
129
+ const queryBuilder = new QueryBuilder_1.QueryBuilder();
130
+ queryBuilder.setModelMapping(this);
131
+ queryBuilder.table(this.__table);
132
+ queryBuilder.where(this.__primaryKey, "=", this[this.__primaryKey]);
133
+ yield queryBuilder.delete({ mode: "deleteOne" });
134
+ this.__is_deleted = true;
135
+ return true;
136
+ });
137
+ }
138
+ }
139
+ exports.Model = Model;
@@ -0,0 +1,15 @@
1
+ export declare class QueryBuilder {
2
+ database: string | null;
3
+ query: any[];
4
+ queryTable: string;
5
+ mode: string;
6
+ modelMapping: null;
7
+ setModelMapping(model?: any | null): void;
8
+ table(table: string): void;
9
+ where(column: any, operator: any, value: any): void;
10
+ get(options?: any): Promise<any>;
11
+ first(options?: any): Promise<any>;
12
+ delete(options?: {
13
+ mode: string;
14
+ }): Promise<boolean>;
15
+ }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.QueryBuilder = void 0;
13
+ const DBConnection_1 = require("./DBConnection");
14
+ class QueryBuilder {
15
+ constructor() {
16
+ this.database = null;
17
+ this.query = [];
18
+ this.queryTable = "";
19
+ this.mode = "get";
20
+ this.modelMapping = null;
21
+ }
22
+ setModelMapping(model) {
23
+ this.modelMapping = model;
24
+ }
25
+ table(table) {
26
+ this.queryTable = table;
27
+ }
28
+ where(column, operator, value) {
29
+ this.query.push({
30
+ type: "where",
31
+ column: column,
32
+ operator: operator,
33
+ value: value,
34
+ });
35
+ }
36
+ get(options) {
37
+ return __awaiter(this, void 0, void 0, function* () {
38
+ this.mode = "get";
39
+ const result = yield DBConnection_1.DBConnection.runQuery(this);
40
+ if (options && options.disableModelMapping) {
41
+ return result && result.length > 0 ? result : null;
42
+ }
43
+ return result && result.length > 0 && this.modelMapping !== null
44
+ ? result.map((el) => DBConnection_1.DBConnection.mapDataToModel(this.modelMapping, el))
45
+ : result && result.length > 0
46
+ ? result
47
+ : null;
48
+ });
49
+ }
50
+ first(options) {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ this.mode = "first";
53
+ const result = yield DBConnection_1.DBConnection.runQuery(this);
54
+ if (options && options.disableModelMapping) {
55
+ return result ? result : null;
56
+ }
57
+ return result && this.modelMapping !== null
58
+ ? DBConnection_1.DBConnection.mapDataToModel(this.modelMapping, result)
59
+ : null;
60
+ });
61
+ }
62
+ delete(options) {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ this.mode =
65
+ options && options.mode === "deleteOne" ? "deleteOne" : "delete";
66
+ yield DBConnection_1.DBConnection.runQuery(this);
67
+ return true;
68
+ });
69
+ }
70
+ }
71
+ exports.QueryBuilder = QueryBuilder;
@@ -0,0 +1,12 @@
1
+ export type Request = {
2
+ body?: any;
3
+ bodyPlain?: any;
4
+ params: object;
5
+ httpVersionMajor: any;
6
+ httpVersionMinor: any;
7
+ httpVersion: any;
8
+ headers: object;
9
+ rawHeaders: object;
10
+ url: string;
11
+ method: string;
12
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,33 @@
1
+ /// <reference types="node" />
2
+ import { ServerResponse } from "http";
3
+ export declare class Response {
4
+ res?: ServerResponse;
5
+ /**
6
+ * Sets the ServerResponse (res) Object (nodejs/http module)
7
+ * @param res
8
+ * @returns
9
+ */
10
+ setServerResponse(res: ServerResponse): this;
11
+ /**
12
+ * Set the http-status-code
13
+ *
14
+ * @param status
15
+ * @returns
16
+ */
17
+ status(status: number): Response;
18
+ /**
19
+ * Set a header attribute: Content-Type: application/json
20
+ *
21
+ * @param type
22
+ * @param value
23
+ * @returns
24
+ */
25
+ header(type: string, value: string): this;
26
+ /**
27
+ * Sends data to the client
28
+ * Any objects will be stringified to JSON
29
+ *
30
+ * @param content
31
+ */
32
+ send(content: any): void;
33
+ }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Response = void 0;
4
+ class Response {
5
+ /**
6
+ * Sets the ServerResponse (res) Object (nodejs/http module)
7
+ * @param res
8
+ * @returns
9
+ */
10
+ setServerResponse(res) {
11
+ this.res = res;
12
+ return this;
13
+ }
14
+ /**
15
+ * Set the http-status-code
16
+ *
17
+ * @param status
18
+ * @returns
19
+ */
20
+ status(status) {
21
+ if (!this.res) {
22
+ return this;
23
+ }
24
+ this.res.statusCode = status;
25
+ return this;
26
+ }
27
+ /**
28
+ * Set a header attribute: Content-Type: application/json
29
+ *
30
+ * @param type
31
+ * @param value
32
+ * @returns
33
+ */
34
+ header(type, value) {
35
+ if (!this.res) {
36
+ return this;
37
+ }
38
+ this.res.setHeader(type, value);
39
+ return this;
40
+ }
41
+ /**
42
+ * Sends data to the client
43
+ * Any objects will be stringified to JSON
44
+ *
45
+ * @param content
46
+ */
47
+ send(content) {
48
+ var _a, _b, _c;
49
+ if (typeof content === "object") {
50
+ (_a = this.res) === null || _a === void 0 ? void 0 : _a.setHeader("Content-Type", "application/json");
51
+ (_b = this.res) === null || _b === void 0 ? void 0 : _b.write(JSON.stringify(content));
52
+ }
53
+ else {
54
+ (_c = this.res) === null || _c === void 0 ? void 0 : _c.write(content);
55
+ }
56
+ }
57
+ }
58
+ exports.Response = Response;
@@ -0,0 +1,48 @@
1
+ export declare class RouteFacade {
2
+ tempGroupPrefix: string | null;
3
+ tempGroupMiddleware: string[] | null;
4
+ /**
5
+ * Register a GET-Method
6
+ *
7
+ * @param path
8
+ * @param component
9
+ * @param options
10
+ */
11
+ get(path: string, component: any, options?: {
12
+ [key: string]: any;
13
+ }): void;
14
+ /**
15
+ * Register a POST-Method
16
+ *
17
+ * @param path
18
+ * @param component
19
+ * @param options
20
+ */
21
+ post(path: string, component: any, options?: {
22
+ [key: string]: any;
23
+ }): void;
24
+ /**
25
+ * Register a PUT-Method
26
+ *
27
+ * @param path
28
+ * @param component
29
+ * @param options
30
+ */
31
+ put(path: string, component: any, options?: {
32
+ [key: string]: any;
33
+ }): void;
34
+ /**
35
+ * Register a DELETE-Method
36
+ *
37
+ * @param path
38
+ * @param component
39
+ * @param options
40
+ */
41
+ delete(path: string, component: any, options?: {
42
+ [key: string]: any;
43
+ }): void;
44
+ group(config: {
45
+ [key: string]: any;
46
+ }, children: any): void;
47
+ }
48
+ export declare const Route: RouteFacade;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Route = exports.RouteFacade = void 0;
4
+ const Router_1 = require("./Router");
5
+ class RouteFacade {
6
+ constructor() {
7
+ this.tempGroupPrefix = null;
8
+ this.tempGroupMiddleware = null;
9
+ }
10
+ /**
11
+ * Register a GET-Method
12
+ *
13
+ * @param path
14
+ * @param component
15
+ * @param options
16
+ */
17
+ get(path, component, options) {
18
+ Router_1.Router.register("GET", (this.tempGroupPrefix ? this.tempGroupPrefix : "") + path, component, options || this.tempGroupMiddleware
19
+ ? Object.assign(Object.assign({}, (options ? options : {})), { middleware: this.tempGroupMiddleware || (options && options.middleware)
20
+ ? [
21
+ ...(this.tempGroupMiddleware
22
+ ? this.tempGroupMiddleware
23
+ : []),
24
+ ...(options && options.middleware
25
+ ? options.middleware
26
+ : []),
27
+ ]
28
+ : null }) : {});
29
+ }
30
+ /**
31
+ * Register a POST-Method
32
+ *
33
+ * @param path
34
+ * @param component
35
+ * @param options
36
+ */
37
+ post(path, component, options) {
38
+ Router_1.Router.register("POST", (this.tempGroupPrefix ? this.tempGroupPrefix : "") + path, component, options || this.tempGroupMiddleware
39
+ ? Object.assign(Object.assign({}, (options ? options : {})), { middleware: this.tempGroupMiddleware || (options && options.middleware)
40
+ ? [
41
+ ...(this.tempGroupMiddleware
42
+ ? this.tempGroupMiddleware
43
+ : []),
44
+ ...(options && options.middleware
45
+ ? options.middleware
46
+ : []),
47
+ ]
48
+ : null }) : {});
49
+ }
50
+ /**
51
+ * Register a PUT-Method
52
+ *
53
+ * @param path
54
+ * @param component
55
+ * @param options
56
+ */
57
+ put(path, component, options) {
58
+ Router_1.Router.register("PUT", (this.tempGroupPrefix ? this.tempGroupPrefix : "") + path, component, options || this.tempGroupMiddleware
59
+ ? Object.assign(Object.assign({}, (options ? options : {})), { middleware: this.tempGroupMiddleware || (options && options.middleware)
60
+ ? [
61
+ ...(this.tempGroupMiddleware
62
+ ? this.tempGroupMiddleware
63
+ : []),
64
+ ...(options && options.middleware
65
+ ? options.middleware
66
+ : []),
67
+ ]
68
+ : null }) : {});
69
+ }
70
+ /**
71
+ * Register a DELETE-Method
72
+ *
73
+ * @param path
74
+ * @param component
75
+ * @param options
76
+ */
77
+ delete(path, component, options) {
78
+ Router_1.Router.register("DELETE", (this.tempGroupPrefix ? this.tempGroupPrefix : "") + path, component, options || this.tempGroupMiddleware
79
+ ? Object.assign(Object.assign({}, (options ? options : {})), { middleware: this.tempGroupMiddleware || (options && options.middleware)
80
+ ? [
81
+ ...(this.tempGroupMiddleware
82
+ ? this.tempGroupMiddleware
83
+ : []),
84
+ ...(options && options.middleware
85
+ ? options.middleware
86
+ : []),
87
+ ]
88
+ : null }) : {});
89
+ }
90
+ group(config, children) {
91
+ // Handle group prefix
92
+ if (config && config.prefix && config.prefix.trim() !== "") {
93
+ this.tempGroupPrefix =
94
+ (this.tempGroupPrefix ? this.tempGroupPrefix : "") + config.prefix;
95
+ }
96
+ // Handle group middleware
97
+ if (config && config.middleware && config.middleware.length > 0) {
98
+ if (!this.tempGroupMiddleware || this.tempGroupMiddleware.length === 0) {
99
+ this.tempGroupMiddleware = config.middleware;
100
+ }
101
+ else {
102
+ this.tempGroupMiddleware = [
103
+ ...this.tempGroupMiddleware,
104
+ ...config.middleware,
105
+ ];
106
+ }
107
+ }
108
+ // Handle children / group body
109
+ children();
110
+ // Reset temp-group data
111
+ this.tempGroupPrefix = null;
112
+ this.tempGroupMiddleware = null;
113
+ }
114
+ }
115
+ exports.RouteFacade = RouteFacade;
116
+ exports.Route = new RouteFacade();
@@ -0,0 +1,100 @@
1
+ /// <reference types="node" />
2
+ import { IncomingMessage, ServerResponse } from "http";
3
+ type RouteObject = {
4
+ path: string;
5
+ component: any;
6
+ options: {
7
+ [key: string]: any;
8
+ };
9
+ params: object;
10
+ };
11
+ declare class RouterFacade {
12
+ /**
13
+ * GET Route Store
14
+ */
15
+ routesGET: {
16
+ [key: string]: {
17
+ path: string;
18
+ component: any;
19
+ options: object;
20
+ params?: object;
21
+ };
22
+ };
23
+ /**
24
+ * POST Route Store
25
+ */
26
+ routesPOST: {
27
+ [key: string]: {
28
+ path: string;
29
+ component: any;
30
+ options: object;
31
+ params?: object;
32
+ };
33
+ };
34
+ /**
35
+ * PUT Route Store
36
+ */
37
+ routesPUT: {
38
+ [key: string]: {
39
+ path: string;
40
+ component: any;
41
+ options: object;
42
+ params?: object;
43
+ };
44
+ };
45
+ /**
46
+ * DELETE Route Store
47
+ */
48
+ routesDELETE: {
49
+ [key: string]: {
50
+ path: string;
51
+ component: any;
52
+ options: object;
53
+ params?: object;
54
+ };
55
+ };
56
+ /**
57
+ * Load the application-routes
58
+ *
59
+ */
60
+ init(): void;
61
+ /**
62
+ * Register a route
63
+ *
64
+ * @param type
65
+ * @param path
66
+ * @param component
67
+ * @param options
68
+ */
69
+ register(type: string, path: string, component: any, options: object): void;
70
+ /**
71
+ * Loads the matching route based on the request-url
72
+ *
73
+ * @param req
74
+ * @returns
75
+ */
76
+ dissolve(req: IncomingMessage): RouteObject | null;
77
+ /**
78
+ * Dissolves the matching route based on the request-url and an object of routes
79
+ *
80
+ * @param routes
81
+ * @param url
82
+ * @returns
83
+ */
84
+ dissolveRoute(routes: any, url: string): any;
85
+ /**
86
+ * Sends the default 404-Page
87
+ *
88
+ * @param res
89
+ */
90
+ sendError(res: ServerResponse, code: number, message?: string): void;
91
+ /**
92
+ * Processes a request
93
+ *
94
+ * @param req
95
+ * @param res
96
+ */
97
+ handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void>;
98
+ }
99
+ export declare const Router: RouterFacade;
100
+ export {};
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.Router = void 0;
16
+ const qs_1 = __importDefault(require("qs"));
17
+ const Response_1 = require("./Response");
18
+ // @ts-ignore
19
+ const Kernel_1 = require("../../../../../app/Kernel");
20
+ class RouterFacade {
21
+ constructor() {
22
+ /**
23
+ * GET Route Store
24
+ */
25
+ this.routesGET = {};
26
+ /**
27
+ * POST Route Store
28
+ */
29
+ this.routesPOST = {};
30
+ /**
31
+ * PUT Route Store
32
+ */
33
+ this.routesPUT = {};
34
+ /**
35
+ * DELETE Route Store
36
+ */
37
+ this.routesDELETE = {};
38
+ }
39
+ /**
40
+ * Load the application-routes
41
+ *
42
+ */
43
+ init() {
44
+ // Load routes
45
+ require(process.cwd() + "/app/routes");
46
+ }
47
+ /**
48
+ * Register a route
49
+ *
50
+ * @param type
51
+ * @param path
52
+ * @param component
53
+ * @param options
54
+ */
55
+ register(type, path, component, options) {
56
+ if (type === "GET") {
57
+ this.routesGET[path] = {
58
+ path: path,
59
+ component: component,
60
+ options: options,
61
+ };
62
+ }
63
+ else if (type === "POST") {
64
+ this.routesPOST[path] = {
65
+ path: path,
66
+ component: component,
67
+ options: options,
68
+ };
69
+ }
70
+ }
71
+ /**
72
+ * Loads the matching route based on the request-url
73
+ *
74
+ * @param req
75
+ * @returns
76
+ */
77
+ dissolve(req) {
78
+ if (!req.url) {
79
+ return null;
80
+ }
81
+ if (req.method === "GET") {
82
+ return this.dissolveRoute(this.routesGET, req.url);
83
+ }
84
+ else if (req.method === "POST") {
85
+ return this.dissolveRoute(this.routesPOST, req.url);
86
+ }
87
+ else if (req.method === "PUT") {
88
+ return this.dissolveRoute(this.routesPUT, req.url);
89
+ }
90
+ else if (req.method === "DELETE") {
91
+ return this.dissolveRoute(this.routesDELETE, req.url);
92
+ }
93
+ return null;
94
+ }
95
+ /**
96
+ * Dissolves the matching route based on the request-url and an object of routes
97
+ *
98
+ * @param routes
99
+ * @param url
100
+ * @returns
101
+ */
102
+ dissolveRoute(routes, url) {
103
+ if (routes[url]) {
104
+ // If url matches directly -> instant return
105
+ return Object.assign(Object.assign({}, routes[url]), { params: {} });
106
+ }
107
+ else {
108
+ // Try to find the matching route: Run through the slash-separated parts of the route
109
+ const partsRequest = url.split("/");
110
+ for (let path in routes) {
111
+ let status = true;
112
+ const parts = path.split("/");
113
+ const params = {};
114
+ for (let i in partsRequest) {
115
+ if (partsRequest[i] !== parts[i]) {
116
+ // Handle URL-Params
117
+ if (parts[i] && parts[i].trim().substring(0, 1) === ":") {
118
+ params[parts[i].trim().substring(1).toString()] = partsRequest[i];
119
+ continue;
120
+ }
121
+ status = false;
122
+ continue;
123
+ }
124
+ }
125
+ if (status) {
126
+ return Object.assign(Object.assign({}, routes[path]), { params: params });
127
+ }
128
+ }
129
+ }
130
+ }
131
+ /**
132
+ * Sends the default 404-Page
133
+ *
134
+ * @param res
135
+ */
136
+ sendError(res, code, message) {
137
+ res.writeHead(code, { "Content-Type": "text/html" });
138
+ res.end(message
139
+ ? message
140
+ : code === 404
141
+ ? "Oops! Page not found ..."
142
+ : "Oops! There was an unexpected error ...");
143
+ }
144
+ /**
145
+ * Processes a request
146
+ *
147
+ * @param req
148
+ * @param res
149
+ */
150
+ handleRequest(req, res) {
151
+ return __awaiter(this, void 0, void 0, function* () {
152
+ const route = this.dissolve(req);
153
+ // Check-Middleware
154
+ if (route &&
155
+ route.options &&
156
+ route.options.middleware &&
157
+ route.options.middleware.length > 0) {
158
+ for (let middlewareKey of route.options.middleware) {
159
+ const middleware = Kernel_1.Kernel.middleware[middlewareKey];
160
+ if (!middleware) {
161
+ return this.sendError(res, 500, "Unknown middleware `" + middlewareKey + "` ...");
162
+ }
163
+ try {
164
+ yield new Promise((resolve, reject) => {
165
+ try {
166
+ middleware(resolve, (status, data) => {
167
+ reject({ status: status, data: data });
168
+ }, req, res);
169
+ }
170
+ catch (e) {
171
+ console.error(e);
172
+ return this.sendError(res, 500, "Error in middleware `" + middlewareKey + "` ...");
173
+ }
174
+ });
175
+ }
176
+ catch (e) {
177
+ // Send Middleware-Abort
178
+ res.writeHead(e.status, typeof e.data === "object"
179
+ ? { "Content-Type": "application/json" }
180
+ : { "Content-Type": "text/html" });
181
+ res.end(typeof e.data === "object"
182
+ ? JSON.stringify(e.data)
183
+ : e.data
184
+ ? e.data
185
+ : " ");
186
+ return;
187
+ }
188
+ }
189
+ }
190
+ // Resolve route-component (handle controller definition)
191
+ if (route && typeof route.component === "string") {
192
+ const split = route.component.split("@");
193
+ const controller = Kernel_1.Kernel.controller[split[0]];
194
+ if (!controller) {
195
+ res.writeHead(500, { "Content-Type": "text/html" });
196
+ res.end("Controller `" + split[0] + "` not found ...");
197
+ return;
198
+ }
199
+ // Set Controller method as route-component
200
+ const controllerInstance = new controller();
201
+ route.component = controllerInstance[split[1]];
202
+ }
203
+ if (route && route.component !== undefined) {
204
+ let body = [];
205
+ const bodyPlain = yield new Promise((resolve) => {
206
+ req
207
+ .on("data", (chunk) => {
208
+ body.push(chunk);
209
+ })
210
+ .on("end", () => {
211
+ resolve(Buffer.concat(body).toString());
212
+ });
213
+ });
214
+ try {
215
+ yield route.component({
216
+ body: bodyPlain ? qs_1.default.parse(bodyPlain) : {},
217
+ bodyPlain: bodyPlain,
218
+ params: route.params,
219
+ httpVersionMajor: req.httpVersionMajor,
220
+ httpVersionMinor: req.httpVersionMinor,
221
+ httpVersion: req.httpVersion,
222
+ headers: req.headers,
223
+ rawHeaders: req.rawHeaders,
224
+ url: req.url,
225
+ method: req.method,
226
+ }, new Response_1.Response().setServerResponse(res));
227
+ res.end();
228
+ }
229
+ catch (e) {
230
+ console.error(e);
231
+ this.sendError(res, 500);
232
+ }
233
+ }
234
+ else {
235
+ this.sendError(res, 404);
236
+ }
237
+ });
238
+ }
239
+ }
240
+ exports.Router = new RouterFacade();
@@ -0,0 +1,7 @@
1
+ export declare class WebApplication {
2
+ private server;
3
+ /**
4
+ * Init the routes and start the http-server
5
+ */
6
+ boot(): void;
7
+ }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.WebApplication = void 0;
7
+ const http_1 = __importDefault(require("http"));
8
+ const Router_1 = require("./Router/Router");
9
+ class WebApplication {
10
+ /**
11
+ * Init the routes and start the http-server
12
+ */
13
+ boot() {
14
+ Router_1.Router.init();
15
+ this.server = http_1.default
16
+ .createServer((req, res) => {
17
+ Router_1.Router.handleRequest(req, res);
18
+ })
19
+ .listen(3000, () => {
20
+ console.log("Server started and listening on port 3000");
21
+ });
22
+ }
23
+ }
24
+ exports.WebApplication = WebApplication;
package/lib/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export * from "./BaseKernel";
2
+ export * from "./Controller/Controller";
3
+ export * from "./WebApplication";
4
+ export * from "./Router/Route";
5
+ export * from "./Router/Request";
6
+ export * from "./Router/Response";
7
+ export * from "./Database/Model";
8
+ export * from "./Database/QueryBuilder";
package/lib/index.js ADDED
@@ -0,0 +1,24 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./BaseKernel"), exports);
18
+ __exportStar(require("./Controller/Controller"), exports);
19
+ __exportStar(require("./WebApplication"), exports);
20
+ __exportStar(require("./Router/Route"), exports);
21
+ __exportStar(require("./Router/Request"), exports);
22
+ __exportStar(require("./Router/Response"), exports);
23
+ __exportStar(require("./Database/Model"), exports);
24
+ __exportStar(require("./Database/QueryBuilder"), exports);
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@webtypen/webframez-core",
3
- "version": "0.0.2",
3
+ "type": "module",
4
+ "version": "0.0.4",
4
5
  "description": "The core package of the typescript based webframez (web-framework) by webtypen.de",
5
6
  "homepage": "https://webtypen.de/",
6
7
  "license": "MIT",
7
- "main": "index.js",
8
+ "main": "lib/index.js",
8
9
  "author": {
9
10
  "name": "Benedict Romp",
10
11
  "email": "b.romp@webtypen.de",
@@ -17,8 +18,19 @@
17
18
  "type": "git",
18
19
  "url": "git+https://github.com/webtypen/webframez-core.git"
19
20
  },
21
+ "scripts": {
22
+ "build": "tsc",
23
+ "build:check": "tsc --noEmit"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^18.11.9",
27
+ "@types/qs": "^6.9.7",
28
+ "ts-node": "^10.9.1",
29
+ "typescript": "^4.9.3"
30
+ },
20
31
  "dependencies": {
21
32
  "dotenv": "^8.2.0",
22
- "lodash": "^4.17.20"
33
+ "lodash": "^4.17.20",
34
+ "qs": "^6.11.0"
23
35
  }
24
36
  }
@@ -1,4 +1,5 @@
1
1
  import { DBDrivers } from "./DBDriver";
2
+ // @ts-ignore
2
3
  import dbconfig from "../../../../../config/database";
3
4
  import { QueryBuilder } from "./QueryBuilder";
4
5
 
@@ -39,6 +40,10 @@ class DBConnectionFacade {
39
40
  connectionName = dbconfig.defaultConnection;
40
41
  }
41
42
 
43
+ if (!connectionName) {
44
+ return null;
45
+ }
46
+
42
47
  if (
43
48
  this.connections[connectionName] &&
44
49
  this.connections[connectionName].driver
@@ -1,6 +1,7 @@
1
1
  import qs from "qs";
2
2
  import { IncomingMessage, ServerResponse } from "http";
3
3
  import { Response } from "./Response";
4
+ // @ts-ignore
4
5
  import { Kernel } from "../../../../../app/Kernel";
5
6
 
6
7
  type RouteObject = {
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ export * from "./BaseKernel";
2
+ export * from "./Controller/Controller";
3
+ export * from "./WebApplication";
4
+ export * from "./Router/Route";
5
+ export * from "./Router/Request";
6
+ export * from "./Router/Response";
7
+ export * from "./Database/Model";
8
+ export * from "./Database/QueryBuilder";
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es6",
4
+ "module": "commonjs",
5
+ "moduleResolution": "node",
6
+ "esModuleInterop": true,
7
+ "resolveJsonModule": true,
8
+ "lib": ["es6", "es2016"],
9
+ "types": ["node"],
10
+ "declaration": true,
11
+ "outDir": "lib",
12
+ "rootDir": "src",
13
+ "strict": true
14
+ },
15
+ "exclude": ["lib", "node_modules", "src/**/*.spec.ts"],
16
+ "include": ["src"]
17
+ }
package/index.ts DELETED
@@ -1,8 +0,0 @@
1
- export * from "./src/BaseKernel";
2
- export * from "./src/Controller/Controller";
3
- export * from "./src/WebApplication";
4
- export * from "./src/Router/Route";
5
- export * from "./src/Router/Request";
6
- export * from "./src/Router/Response";
7
- export * from "./src/Database/Model";
8
- export * from "./src/Database/QueryBuilder";