@oino-ts/common 0.1.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/README.md +190 -0
- package/dist/cjs/OINOBenchmark.js +108 -0
- package/dist/cjs/OINOHtmlTemplate.js +177 -0
- package/dist/cjs/OINOLog.js +151 -0
- package/dist/cjs/OINOParser.js +466 -0
- package/dist/cjs/OINOResult.js +216 -0
- package/dist/cjs/OINOStr.js +265 -0
- package/dist/cjs/index.js +40 -0
- package/dist/esm/OINOBenchmark.js +104 -0
- package/dist/esm/OINOHtmlTemplate.js +173 -0
- package/dist/esm/OINOLog.js +146 -0
- package/dist/esm/OINOParser.js +462 -0
- package/dist/esm/OINOResult.js +211 -0
- package/dist/esm/OINOStr.js +261 -0
- package/dist/esm/index.js +29 -0
- package/dist/types/OINOBenchmark.d.ts +49 -0
- package/dist/types/OINOHtmlTemplate.d.ts +88 -0
- package/dist/types/OINOLog.d.ts +105 -0
- package/dist/types/OINOParser.d.ts +53 -0
- package/dist/types/OINOResult.d.ts +110 -0
- package/dist/types/OINOStr.d.ts +108 -0
- package/dist/types/index.d.ts +29 -0
- package/package.json +30 -0
- package/src/OINOBenchmark.ts +112 -0
- package/src/OINOHtmlTemplate.ts +186 -0
- package/src/OINOLog.ts +168 -0
- package/src/OINOResult.ts +234 -0
- package/src/OINOStr.ts +254 -0
- package/src/index.ts +31 -0
package/README.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# OINO TS
|
|
2
|
+
OINO Is Not an ORM but it's trying to solve a similar problem for API development. Instead of mirroring your DB schema in code that needs manual updates, OINO will get the data schema from DBMS using SQL in real time. Every time your app starts, it has an updated data model which enables automatic (de)serialize SQL results to JSON/CSV and back. OINO works on the level below routing where you pass the method, URL ID, body and request parameters to the API-object. OINO will parse and validate the data against the data model and generate proper SQL for your DB. Because OINO knows how data is serialized (e.g. JSON), what column it belongs to (e.g. floating point number) and what the target database is, it knows how to parse, format and escape the value as valid SQL.
|
|
3
|
+
|
|
4
|
+
```
|
|
5
|
+
const result:OINOApiResult = await api_orderdetails.doRequest("GET", id, body, params)
|
|
6
|
+
return new Response(result.modelset.writeString(OINOContentType.json))
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# GETTING STARTED
|
|
11
|
+
|
|
12
|
+
### Setup
|
|
13
|
+
Install the `@oino-ts/db` npm package and necessary database packages and import them in your code.
|
|
14
|
+
```
|
|
15
|
+
bun install @oino-ts/db
|
|
16
|
+
bun install @oino-ts/db-bunsqlite
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
import { OINODb, OINOApi, OINOFactory } from "@oino-ts/db";
|
|
21
|
+
import { OINODbBunSqlite } from "@oino-ts/db-bunsqlite"
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
### Register database and logger
|
|
25
|
+
Register your database implementation and logger (see [`OINOConsoleLog`](https://pragmatta.github.io/oino-ts/classes/types_src.OINOConsoleLog.html) how to implement your own)
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
OINOLog.setLogger(new OINOConsoleLog())
|
|
29
|
+
OINOFactory.registerDb("OINODbBunSqlite", OINODbBunSqlite)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Create a database
|
|
33
|
+
Creating a database connection [`OINODb`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODb.html) is done by passing [`OINODbParams`](https://pragmatta.github.io/oino-ts/types/db_src.OINODbParams.html) to the factory method. For [`OINODbBunSqlite`](https://pragmatta.github.io/oino-ts/classes/db_bunsqlite_src.OINODbBunSqlite.html) that means a file url for the database file, for others network host, port, credentials etc.
|
|
34
|
+
```
|
|
35
|
+
const db:OINODb = await OINOFactory.createDb( { type: "OINODbBunSqlite", url: "file://../localDb/northwind.sqlite" } )
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Create an API
|
|
39
|
+
From a database you can create an [`OINOApi`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbApi.html) by passing [`OINOApiParams`](https://pragmatta.github.io/oino-ts/types/db_src.OINODbApiParams.html) with table name and preferences to the factory method.
|
|
40
|
+
```
|
|
41
|
+
const api_employees:OINOApi = await OINOFactory.createApi(db, { tableName: "Employees", excludeFields:["BirthDate"] })
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Pass HTTP requests to API
|
|
45
|
+
When you receive a HTTP request, just pass the method, URL ID, body and params to the correct API, which will parse and validate input and return results.
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
const result:OINOApiResult = await api_orderdetails.doRequest("GET", id, body, params)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Write results back to HTTP Response
|
|
52
|
+
The results for a GET request will contain [`OINOModelSet`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbModelSet.html) data that can be written out as JSON or CSV as needed. For other requests result is just success or error with messages.
|
|
53
|
+
```
|
|
54
|
+
return new Response(result.data.writeString(OINOContentType.json))
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# FEATURES
|
|
59
|
+
|
|
60
|
+
## RESTfull
|
|
61
|
+
OINO maps HTTP methods GET/POST/PUT/DELETE to SQL operations SELECT/INSERT/UPDATE/DELETE. The GET/POST requests can be made without URL ID to get all rows or insert new ones and others target a single row using URL ID.
|
|
62
|
+
|
|
63
|
+
For example HTTP POST
|
|
64
|
+
```
|
|
65
|
+
Request and response:
|
|
66
|
+
> curl.exe -X POST http://localhost:3001/orderdetails -H "Content-Type: application/json" --data '[{\"OrderID\":11077,\"ProductID\":99,\"UnitPrice\":19,\"Quantity\":1,\"Discount\":0}]'
|
|
67
|
+
{"success":true,"statusCode":200,"statusMessage":"OK","messages":[]}
|
|
68
|
+
|
|
69
|
+
SQL:
|
|
70
|
+
INSERT INTO [OrderDetails] ("OrderID","ProductID","UnitPrice","Quantity","Discount") VALUES (11077,99,19,1,0);
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
## Universal Serialization
|
|
75
|
+
OINO handles serialization of data to JSON/CSV/etc. and back based on the data model. It knows what columns exist, what is their data type and how to convert each to JSON/CSV and back. This allows also partial data to be sent, i.e. you can send only columns that need updating or even send extra columns and have them ignored.
|
|
76
|
+
|
|
77
|
+
### Features
|
|
78
|
+
- Files can be sent to BLOB fields using BASE64 or MIME multipart encoding. Also supports standard HTML form file submission to blob fields and returning them data url images.
|
|
79
|
+
- Datetimes are (optionally) normalized to ISO 8601 format.
|
|
80
|
+
- Extended JSON-encoding
|
|
81
|
+
- Unquoted literal `undefined` can be used to represent non-existent values (leaving property out works too but preserving structure might be easier e.g. when translating data).
|
|
82
|
+
- CSV
|
|
83
|
+
- Comma-separated, doublequotes.
|
|
84
|
+
- Unquoted literal `null` represents null values.
|
|
85
|
+
- Unquoted empty string represents undefined values.
|
|
86
|
+
- Form data
|
|
87
|
+
- Multipart-mixed and binary files not supported.
|
|
88
|
+
- Non-existent value line (i.e. nothing after the empty line) treated as a null value.
|
|
89
|
+
- Url-encoded
|
|
90
|
+
- No null values, missing properties treated as undefined.
|
|
91
|
+
- Multiple lines could be used to post multiple rows.
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
## Database Abstraction
|
|
95
|
+
OINO functions as a database abstraction, providing a consistent interface for working with different databases. It abstracts out different conventions in connecting, making queries and formatting data.
|
|
96
|
+
|
|
97
|
+
Currently supported databases:
|
|
98
|
+
- Bun Sqlite through Bun native implementation
|
|
99
|
+
- Postgresql through [pg](https://www.npmjs.com/package/pg)-package
|
|
100
|
+
- Mariadb / Mysql-support through [mariadb](https://www.npmjs.com/package/mariadb)-package
|
|
101
|
+
- Sql Server through [mssql](https://www.npmjs.com/package/mssql)-package
|
|
102
|
+
|
|
103
|
+
## Composite Keys
|
|
104
|
+
To support tables with multipart primary keys OINO generates a composite key `_OINOID_` that is included in the result and can be used as the REST ID. For example in the example above table `OrderDetails` has two primary keys `OrderID` and `ProductID` making the `_OINOID_` of form `11077:99`.
|
|
105
|
+
|
|
106
|
+
## Power Of SQL
|
|
107
|
+
Since OINO is just generating SQL, WHERE-conditions can be defined with [`OINOSqlFilter`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbSqlFilter.html), order with [`OINOSqlOrder`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbSqlOrder.html) and limits/paging with [`OINOSqlLimit`](https://pragmatta.github.io/oino-ts/classes/db_src.OINODbSqlLimit.html) that are passed as HTTP request parameters. No more API development where you make unique API endpoints for each filter that fetch all data with original API and filter in backend code. Every API can be filtered when and as needed without unnessecary data tranfer and utilizing SQL indexing when available.
|
|
108
|
+
|
|
109
|
+
## Swagger Support
|
|
110
|
+
Swagger is great as long as the definitions are updated and with OINO you can automatically get a Swagger definition including a data model schema.
|
|
111
|
+
```
|
|
112
|
+
if (url.pathname == "/swagger.json") {
|
|
113
|
+
return new Response(JSON.stringify(OINOSwagger.getApiDefinition(api_array)))
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+

|
|
117
|
+
|
|
118
|
+
## Node support
|
|
119
|
+
OINO is developped Typescript first but compiles to standard CommonJS and the NPM packages should work on either ESM / CommonJS. Checkout sample apps `readmeApp` (ESM) and `nodeApp` (CommonJS).
|
|
120
|
+
|
|
121
|
+
## HTMX support
|
|
122
|
+
OINO is [htmx.org](https://htmx.org) friendly, allowing easy translation of [`OINODataRow`](https://pragmatta.github.io/oino-ts/types/db_src.OINODataRow.html) to HTML output using templates (cf. the [htmx sample app](https://github.com/pragmatta/oino-ts/tree/main/samples/htmxApp)).
|
|
123
|
+
|
|
124
|
+
## Hashids
|
|
125
|
+
Autoinc numeric id's are very pragmatic and fit well with OINO (e.g. using a form without primary key fields to insert new rows with database assigned ids). However it's not always sensible to share information about the sequence. Hashids solve this by masking the original values by encrypting the ids using AES-128 and some randomness. Length of the hashid can be chosen from 12-32 characters where longer ids provide more security. However this should not be considereded a cryptographic solution for keeping ids secret but rather making it infeasible to iterate all ids.
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# STATUS
|
|
129
|
+
OINO is currently a hobby project which should and should considered in alpha status. That also means compatibility breaking changes can be made without prior notice when architectual issues are discovered.
|
|
130
|
+
|
|
131
|
+
## Beta
|
|
132
|
+
For a beta status following milestones are planned:
|
|
133
|
+
|
|
134
|
+
### Realistic app
|
|
135
|
+
There needs to be a realistic app built on top of OINO to get a better grasp of the edge cases.
|
|
136
|
+
|
|
137
|
+
## Roadmap
|
|
138
|
+
Things that need to happen in some order before beta-status are at least following:
|
|
139
|
+
|
|
140
|
+
### Support for views
|
|
141
|
+
Simple cases of views would work already in some databases but edge cases might get complicated. For example
|
|
142
|
+
- How to handle a view which does not have a complete private key?
|
|
143
|
+
- What edge cases exist in updating views?
|
|
144
|
+
|
|
145
|
+
### Batch updates
|
|
146
|
+
Supporting batch updates similar to batch inserts is slightly bending the RESTfull principles but would still be a useful optional feature.
|
|
147
|
+
|
|
148
|
+
### Aggregation
|
|
149
|
+
Similar to filtering, ordering and limits, aggregation could be implemented as HTTP request parameters telling what column is aggregated or used for ordering or how many results to return.
|
|
150
|
+
|
|
151
|
+
### Streaming
|
|
152
|
+
One core idea is to be efficient in not making unnecessary copies of the data and minimizing garbage collection debt. This can be taken further by implementing streaming, allowing large dataset to be written to HTTP response as SQL result rows are received.
|
|
153
|
+
|
|
154
|
+
### SQL generation callbacks
|
|
155
|
+
It would be useful to allow developer to validate / override SQL generation to cover cases OINO does not support or even workaround issues.
|
|
156
|
+
|
|
157
|
+
### Transactions
|
|
158
|
+
Even though the basic case for OINO is executing SQL operations on individual rows, having an option to use SQL transactions could make sense at least for batch operations.
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# HELP
|
|
162
|
+
|
|
163
|
+
## Bug reports
|
|
164
|
+
Fixing bugs is a priority and getting good quality bug reports helps. It's recommended to use the sample Northwind database included with project to replicate issues or make an SQL script export of the relevant table.
|
|
165
|
+
|
|
166
|
+
## Feedback
|
|
167
|
+
Understanding and prioritizing the use cases for OINO is also important and feedback about how you'd use OINO is interesting. Feel free to raise issues and feature requests in Github, but understand that short term most of the effort goes towards reaching the beta stage.
|
|
168
|
+
|
|
169
|
+
## Typescript / Javascript architecture
|
|
170
|
+
Typescript building with different targets and module-systemts and a ton of configuration is a complex domain and something I have little experience un so help in fixing problems and how thing ought to be done is appreciated.
|
|
171
|
+
|
|
172
|
+
# LINKS
|
|
173
|
+
- [Github repository](https://github.com/pragmatta/oino-ts)
|
|
174
|
+
- [NPM repository](https://www.npmjs.com/org/oino-ts)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# ACKNOWLEDGEMENTS
|
|
178
|
+
|
|
179
|
+
## Libraries
|
|
180
|
+
OINO uses the following open source libraries and npm packages and I would like to thank everyone for their contributions:
|
|
181
|
+
- Postgresql [node-postgres package](https://www.npmjs.com/package/pg)
|
|
182
|
+
- Mariadb / Mysql [mariadb package](https://www.npmjs.com/package/mariadb)
|
|
183
|
+
- Sql Server [mssql package](https://www.npmjs.com/package/mssql)
|
|
184
|
+
- Custom base encoding [base-x package](https://www.npmjs.com/package/base-x)
|
|
185
|
+
|
|
186
|
+
## Bun
|
|
187
|
+
OINO has been developed using the Bun runtime, not because of the speed improvements but for the first class Typescript support and integrated developper experience. Kudos on the bun team for making Typescript work more exiting again.
|
|
188
|
+
|
|
189
|
+
## SQL Scripts
|
|
190
|
+
The SQL scripts for creating the sample Northwind database are based on [Google Code archive](https://code.google.com/archive/p/northwindextended/downloads) and have been further customized to ensure they would have identical data (in the scope of the automated testing).
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
4
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
5
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.OINOBenchmark = void 0;
|
|
9
|
+
/**
|
|
10
|
+
* Static class for benchmarking functions.
|
|
11
|
+
*
|
|
12
|
+
*/
|
|
13
|
+
class OINOBenchmark {
|
|
14
|
+
static _benchmarkCount = {};
|
|
15
|
+
static _benchmarkData = {};
|
|
16
|
+
static _benchmarkEnabled = {};
|
|
17
|
+
static _benchmarkStart = {};
|
|
18
|
+
/**
|
|
19
|
+
* Reset benchmark data (but not what is enabled).
|
|
20
|
+
*
|
|
21
|
+
*/
|
|
22
|
+
static reset() {
|
|
23
|
+
this._benchmarkData = {};
|
|
24
|
+
this._benchmarkCount = {};
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Set benchmark names that are enabled.
|
|
28
|
+
*
|
|
29
|
+
* @param module array of those benchmarks that are enabled
|
|
30
|
+
*/
|
|
31
|
+
static setEnabled(module) {
|
|
32
|
+
this._benchmarkEnabled = {};
|
|
33
|
+
module.forEach(module_name => {
|
|
34
|
+
this._benchmarkEnabled[module_name] = true;
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Start benchmark timing.
|
|
39
|
+
*
|
|
40
|
+
* @param module of the benchmark
|
|
41
|
+
* @param method of the benchmark
|
|
42
|
+
*/
|
|
43
|
+
static start(module, method) {
|
|
44
|
+
const name = module + "." + method;
|
|
45
|
+
if (this._benchmarkEnabled[module]) {
|
|
46
|
+
if (this._benchmarkCount[name] == undefined) {
|
|
47
|
+
this._benchmarkCount[name] = 0;
|
|
48
|
+
this._benchmarkData[name] = 0;
|
|
49
|
+
}
|
|
50
|
+
this._benchmarkStart[name] = performance.now();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Complete benchmark timing
|
|
55
|
+
*
|
|
56
|
+
* @param module of the benchmark
|
|
57
|
+
* @param method of the benchmark
|
|
58
|
+
* @param category optional subcategory of the benchmark
|
|
59
|
+
*/
|
|
60
|
+
static end(module, method, category) {
|
|
61
|
+
const name = module + "." + method;
|
|
62
|
+
let result = 0;
|
|
63
|
+
if (this._benchmarkEnabled[module]) {
|
|
64
|
+
const duration = performance.now() - this._benchmarkStart[name];
|
|
65
|
+
this._benchmarkCount[name] += 1;
|
|
66
|
+
this._benchmarkData[name] += duration;
|
|
67
|
+
if (category) {
|
|
68
|
+
const category_name = name + "." + category;
|
|
69
|
+
if (this._benchmarkCount[category_name] == undefined) {
|
|
70
|
+
this._benchmarkCount[category_name] = 0;
|
|
71
|
+
this._benchmarkData[category_name] = 0;
|
|
72
|
+
}
|
|
73
|
+
this._benchmarkCount[category_name] += 1;
|
|
74
|
+
this._benchmarkData[category_name] += duration;
|
|
75
|
+
}
|
|
76
|
+
result = this._benchmarkData[name] / this._benchmarkCount[name];
|
|
77
|
+
}
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Get given benchmark data.
|
|
82
|
+
*
|
|
83
|
+
* @param module of the benchmark
|
|
84
|
+
* @param method of the benchmark
|
|
85
|
+
*
|
|
86
|
+
*/
|
|
87
|
+
static get(module, method) {
|
|
88
|
+
const name = module + "." + method;
|
|
89
|
+
if (this._benchmarkEnabled[module]) {
|
|
90
|
+
return this._benchmarkData[module] / this._benchmarkCount[module];
|
|
91
|
+
}
|
|
92
|
+
return -1;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Get all benchmark data.
|
|
96
|
+
*
|
|
97
|
+
*/
|
|
98
|
+
static getAll() {
|
|
99
|
+
let result = {};
|
|
100
|
+
for (const name in this._benchmarkData) {
|
|
101
|
+
if (this._benchmarkCount[name] > 0) {
|
|
102
|
+
result[name] = this._benchmarkData[name] / this._benchmarkCount[name];
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
exports.OINOBenchmark = OINOBenchmark;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OINOHtmlTemplate = void 0;
|
|
4
|
+
const _1 = require(".");
|
|
5
|
+
/**
|
|
6
|
+
* Class for rendering HTML from data.
|
|
7
|
+
*/
|
|
8
|
+
class OINOHtmlTemplate {
|
|
9
|
+
_tag;
|
|
10
|
+
_tagCleanRegex;
|
|
11
|
+
_variables = {};
|
|
12
|
+
/** HTML template string */
|
|
13
|
+
template;
|
|
14
|
+
/** Cache modified value for template */
|
|
15
|
+
modified;
|
|
16
|
+
/** Cache expiration value for template */
|
|
17
|
+
expires;
|
|
18
|
+
/**
|
|
19
|
+
* Creates HTML Response from a key-value-pair.
|
|
20
|
+
*
|
|
21
|
+
* @param template template string
|
|
22
|
+
* @param tag tag to identify variables in template
|
|
23
|
+
*
|
|
24
|
+
*/
|
|
25
|
+
constructor(template, tag = "###") {
|
|
26
|
+
this.template = template;
|
|
27
|
+
this.modified = 0;
|
|
28
|
+
this.expires = 0;
|
|
29
|
+
this._tag = tag;
|
|
30
|
+
this._tagCleanRegex = new RegExp(tag + ".*" + tag, "g");
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* @returns whether template is empty
|
|
34
|
+
*/
|
|
35
|
+
isEmpty() {
|
|
36
|
+
return this.template == "";
|
|
37
|
+
}
|
|
38
|
+
_createHttpResult(html, removeUnusedTags) {
|
|
39
|
+
if (removeUnusedTags) {
|
|
40
|
+
html = html.replace(this._tagCleanRegex, "");
|
|
41
|
+
}
|
|
42
|
+
const result = new _1.OINOHttpResult(html);
|
|
43
|
+
if (this.expires >= 1) {
|
|
44
|
+
result.expires = Math.round(this.expires);
|
|
45
|
+
}
|
|
46
|
+
if (this.modified >= 1) {
|
|
47
|
+
result.lastModified = this.modified;
|
|
48
|
+
}
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
_renderHtml() {
|
|
52
|
+
let html = this.template;
|
|
53
|
+
for (let key in this._variables) {
|
|
54
|
+
const value = this._variables[key];
|
|
55
|
+
html = html.replaceAll(this._tag + key + this._tag, value);
|
|
56
|
+
}
|
|
57
|
+
return html;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Clear template variables.
|
|
61
|
+
*
|
|
62
|
+
*/
|
|
63
|
+
clearVariables() {
|
|
64
|
+
this._variables = {};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Sets template variable from a key-value-pair.
|
|
68
|
+
*
|
|
69
|
+
* @param variable key
|
|
70
|
+
* @param value value
|
|
71
|
+
* @param escapeValue whether to escape value
|
|
72
|
+
*
|
|
73
|
+
*/
|
|
74
|
+
setVariableFromValue(variable, value, escapeValue = true) {
|
|
75
|
+
if (escapeValue) {
|
|
76
|
+
value = _1.OINOStr.encode(value, _1.OINOContentType.html);
|
|
77
|
+
}
|
|
78
|
+
this._variables[variable] = value;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Sets template variables from object properties.
|
|
82
|
+
*
|
|
83
|
+
* @param object any object
|
|
84
|
+
* @param escapeValue whether to escape value
|
|
85
|
+
*
|
|
86
|
+
*/
|
|
87
|
+
setVariableFromProperties(object, escapeValue = true) {
|
|
88
|
+
if (object) {
|
|
89
|
+
for (let key in object) {
|
|
90
|
+
if (escapeValue) {
|
|
91
|
+
this._variables[key] = _1.OINOStr.encode(object[key], _1.OINOContentType.html);
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
this._variables[key] = object[key];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Creates HTML Response from set variables.
|
|
101
|
+
*
|
|
102
|
+
* @param removeUnusedTags whether to remove unused tags
|
|
103
|
+
*
|
|
104
|
+
*/
|
|
105
|
+
render(removeUnusedTags = true) {
|
|
106
|
+
return this._createHttpResult(this._renderHtml(), removeUnusedTags);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Creates HTML Response from a key-value-pair.
|
|
110
|
+
*
|
|
111
|
+
* @param key key
|
|
112
|
+
* @param value value
|
|
113
|
+
* @param removeUnusedTags whether to remove unused tags
|
|
114
|
+
*
|
|
115
|
+
*/
|
|
116
|
+
renderFromKeyValue(key, value, removeUnusedTags = true) {
|
|
117
|
+
_1.OINOBenchmark.start("OINOHtmlTemplate", "renderFromKeyValue");
|
|
118
|
+
this.setVariableFromValue(key, value);
|
|
119
|
+
const result = this.render(removeUnusedTags);
|
|
120
|
+
_1.OINOBenchmark.end("OINOHtmlTemplate", "renderFromKeyValue");
|
|
121
|
+
return result;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Creates HTML Response from object properties.
|
|
125
|
+
*
|
|
126
|
+
* @param object object
|
|
127
|
+
* @param removeUnusedTags whether to remove unused tags
|
|
128
|
+
*
|
|
129
|
+
*/
|
|
130
|
+
renderFromObject(object, removeUnusedTags = true) {
|
|
131
|
+
_1.OINOBenchmark.start("OINOHtmlTemplate", "renderFromObject");
|
|
132
|
+
this.setVariableFromProperties(object);
|
|
133
|
+
const result = this.render(removeUnusedTags);
|
|
134
|
+
_1.OINOBenchmark.end("OINOHtmlTemplate", "renderFromObject");
|
|
135
|
+
return result;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Creates HTML Response from API result.
|
|
139
|
+
*
|
|
140
|
+
* @param result OINOResult-object
|
|
141
|
+
* @param removeUnusedTags whether to remove unused tags
|
|
142
|
+
* @param messageSeparator HTML separator for messages
|
|
143
|
+
* @param includeErrorMessages include debug messages in result
|
|
144
|
+
* @param includeWarningMessages include debug messages in result
|
|
145
|
+
* @param includeInfoMessages include debug messages in result
|
|
146
|
+
* @param includeDebugMessages include debug messages in result
|
|
147
|
+
*
|
|
148
|
+
*/
|
|
149
|
+
renderFromResult(result, removeUnusedTags = true, messageSeparator, includeErrorMessages = false, includeWarningMessages = false, includeInfoMessages = false, includeDebugMessages = false) {
|
|
150
|
+
_1.OINOBenchmark.start("OINOHtmlTemplate", "renderFromResult");
|
|
151
|
+
this.setVariableFromValue("statusCode", result.statusCode.toString());
|
|
152
|
+
this.setVariableFromValue("statusMessage", result.statusMessage.toString());
|
|
153
|
+
let messages = [];
|
|
154
|
+
for (let i = 0; i < result.messages.length; i++) {
|
|
155
|
+
if (includeErrorMessages && result.messages[i].startsWith(_1.OINO_ERROR_PREFIX)) {
|
|
156
|
+
messages.push(_1.OINOStr.encode(result.messages[i], _1.OINOContentType.html));
|
|
157
|
+
}
|
|
158
|
+
if (includeWarningMessages && result.messages[i].startsWith(_1.OINO_WARNING_PREFIX)) {
|
|
159
|
+
messages.push(_1.OINOStr.encode(result.messages[i], _1.OINOContentType.html));
|
|
160
|
+
}
|
|
161
|
+
if (includeInfoMessages && result.messages[i].startsWith(_1.OINO_INFO_PREFIX)) {
|
|
162
|
+
messages.push(_1.OINOStr.encode(result.messages[i], _1.OINOContentType.html));
|
|
163
|
+
}
|
|
164
|
+
if (includeDebugMessages && result.messages[i].startsWith(_1.OINO_DEBUG_PREFIX)) {
|
|
165
|
+
messages.push(_1.OINOStr.encode(result.messages[i], _1.OINOContentType.html));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (messages.length > 0) {
|
|
169
|
+
this.setVariableFromValue("messages", messages.join(messageSeparator), false); // messages have been escaped already
|
|
170
|
+
}
|
|
171
|
+
const http_result = this.render(removeUnusedTags);
|
|
172
|
+
_1.OINOBenchmark.end("OINOHtmlTemplate", "renderFromResult");
|
|
173
|
+
return http_result;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
exports.OINOHtmlTemplate = OINOHtmlTemplate;
|
|
177
|
+
;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
4
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
5
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.OINOConsoleLog = exports.OINOLog = exports.OINOLogLevel = void 0;
|
|
9
|
+
/** Logging levels */
|
|
10
|
+
var OINOLogLevel;
|
|
11
|
+
(function (OINOLogLevel) {
|
|
12
|
+
/** Debug messages */
|
|
13
|
+
OINOLogLevel[OINOLogLevel["debug"] = 0] = "debug";
|
|
14
|
+
/** Informational messages */
|
|
15
|
+
OINOLogLevel[OINOLogLevel["info"] = 1] = "info";
|
|
16
|
+
/** Warning messages */
|
|
17
|
+
OINOLogLevel[OINOLogLevel["warn"] = 2] = "warn";
|
|
18
|
+
/** Error messages */
|
|
19
|
+
OINOLogLevel[OINOLogLevel["error"] = 3] = "error";
|
|
20
|
+
})(OINOLogLevel || (exports.OINOLogLevel = OINOLogLevel = {}));
|
|
21
|
+
/**
|
|
22
|
+
* Abstract base class for logging implementations supporting
|
|
23
|
+
* - error, warning, info and debug channels
|
|
24
|
+
* - setting level of logs outputted
|
|
25
|
+
*
|
|
26
|
+
*/
|
|
27
|
+
class OINOLog {
|
|
28
|
+
static _instance;
|
|
29
|
+
_logLevel = OINOLogLevel.warn;
|
|
30
|
+
/**
|
|
31
|
+
* Abstract logging method to implement the actual logging operation.
|
|
32
|
+
*
|
|
33
|
+
* @param logLevel level of the log events
|
|
34
|
+
*
|
|
35
|
+
*/
|
|
36
|
+
constructor(logLevel = OINOLogLevel.warn) {
|
|
37
|
+
// console.log("OINOLog.constructor: logLevel=" + logLevel)
|
|
38
|
+
this._logLevel = logLevel;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Abstract logging method to implement the actual logging operation.
|
|
42
|
+
*
|
|
43
|
+
* @param level level of the log event
|
|
44
|
+
* @param levelStr level string of the log event
|
|
45
|
+
* @param message message of the log event
|
|
46
|
+
* @param data structured data associated with the log event
|
|
47
|
+
*
|
|
48
|
+
*/
|
|
49
|
+
static _log(level, levelStr, message, data) {
|
|
50
|
+
// console.log("_log: level=" + level + ", levelStr=" + levelStr + ", message=" + message + ", data=" + data)
|
|
51
|
+
if ((OINOLog._instance) && (OINOLog._instance._logLevel <= level)) {
|
|
52
|
+
OINOLog._instance?._writeLog(levelStr, message, data);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Set active logger and log level.
|
|
57
|
+
*
|
|
58
|
+
* @param logger logger instance
|
|
59
|
+
*
|
|
60
|
+
*/
|
|
61
|
+
static setLogger(logger) {
|
|
62
|
+
// console.log("setLogger: " + log)
|
|
63
|
+
if (logger) {
|
|
64
|
+
OINOLog._instance = logger;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Set log level.
|
|
69
|
+
*
|
|
70
|
+
* @param logLevel log level to use
|
|
71
|
+
*
|
|
72
|
+
*/
|
|
73
|
+
static setLogLevel(logLevel) {
|
|
74
|
+
if (OINOLog._instance) {
|
|
75
|
+
OINOLog._instance._logLevel = logLevel;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Log error event.
|
|
80
|
+
*
|
|
81
|
+
* @param message message of the log event
|
|
82
|
+
* @param data structured data associated with the log event
|
|
83
|
+
*
|
|
84
|
+
*/
|
|
85
|
+
static error(message, data) {
|
|
86
|
+
OINOLog._log(OINOLogLevel.error, "ERROR", message, data);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Log warning event.
|
|
90
|
+
*
|
|
91
|
+
* @param message message of the log event
|
|
92
|
+
* @param data structured data associated with the log event
|
|
93
|
+
*
|
|
94
|
+
*/
|
|
95
|
+
static warning(message, data) {
|
|
96
|
+
OINOLog._log(OINOLogLevel.warn, "WARN", message, data);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Log info event.
|
|
100
|
+
*
|
|
101
|
+
* @param message message of the log event
|
|
102
|
+
* @param data structured data associated with the log event
|
|
103
|
+
*
|
|
104
|
+
*/
|
|
105
|
+
static info(message, data) {
|
|
106
|
+
OINOLog._log(OINOLogLevel.info, "INFO", message, data);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Log debug event.
|
|
110
|
+
*
|
|
111
|
+
* @param message message of the log event
|
|
112
|
+
* @param data structured data associated with the log event
|
|
113
|
+
*
|
|
114
|
+
*/
|
|
115
|
+
static debug(message, data) {
|
|
116
|
+
OINOLog._log(OINOLogLevel.debug, "DEBUG", message, data);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
exports.OINOLog = OINOLog;
|
|
120
|
+
/**
|
|
121
|
+
* Logging implementation based on console.log.
|
|
122
|
+
*
|
|
123
|
+
*/
|
|
124
|
+
class OINOConsoleLog extends OINOLog {
|
|
125
|
+
/**
|
|
126
|
+
* Constructor of `OINOConsoleLog`
|
|
127
|
+
* @param logLevel logging level
|
|
128
|
+
*/
|
|
129
|
+
constructor(logLevel = OINOLogLevel.warn) {
|
|
130
|
+
super(logLevel);
|
|
131
|
+
}
|
|
132
|
+
_writeLog(level, message, data) {
|
|
133
|
+
let log = "OINOLog " + level + ": " + message;
|
|
134
|
+
if (data) {
|
|
135
|
+
log += " " + JSON.stringify(data);
|
|
136
|
+
}
|
|
137
|
+
if (level == "ERROR") {
|
|
138
|
+
console.error(log);
|
|
139
|
+
}
|
|
140
|
+
else if (level == "WARN") {
|
|
141
|
+
console.warn(log);
|
|
142
|
+
}
|
|
143
|
+
else if (level == "INFO") {
|
|
144
|
+
console.info(log);
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
console.log(log);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
exports.OINOConsoleLog = OINOConsoleLog;
|