1.0.45 • Published 10 months ago

@rainbow-o23/n3 v1.0.45

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Static Badge

TypeORM MySQL PostgreSQL MSSQL Oracle

Module Formats

o23/n3

o23/n3 provides the most basic pipeline steps.

Snippet Supporting

Almost all pipeline steps use dynamic snippets to some extent. In order to facilitate various operations on objects in the snippet, o23/n3 injects rich function support in advance when executing these scripts. All the function support provided by the pipeline steps can be directly obtained and used in scripts using the $helpers handle. For example:

const currentTime = $helpers.$date.now();

When using scripts, pay attention to the usage of variables. Typically:

  • $factor represents the incoming data and can be used in most snippet definitions,
  • $result represents the processed data and only appears in the toResponse snippet of Fragmentary,
  • $request represents the original request data and can be used in almost all snippets, but it is not recommended,
  • $helpers represents function supporting and can be used in all snippets,
  • $options represents a set of data, usually in error handles.

Typescript support

In dynamic snippet, TypeScript syntax can also be used. Currently, o23/n3 is compiled using ES2022 syntax. It is important to note that dynamic script fragments are function bodies, so import/export syntax is not supported. Moreover, they are compiled in loose mode, and the compilation process does not report any errors. Additionally, for script security reasons, the following keywords or classes are also not supported.

  • process
  • global
  • eval
  • Function

Basic Steps

Fragmentary

Usually, when processing logic, we do not need all the memory contexts, but only need to extract certain fragments for processing and return the processing results to the context for subsequent logic to continue processing. Therefore, o23/n3 provides a relevant implementation, allowing pipeline steps to flexibly access the relevant memory data and write back the processed result data to the context in the required format. All pipeline steps should inherit from this implementation to obtain the same capabilities.

Constructor Parameters

NameTypeDefault ValueComments
fromRequestScriptFuncOrBody\Get data from request.
toResponseScriptFuncOrBody\Write data to response.
mergeRequestboolean or stringfalseShortcut to merge data to response.
errorHandles.catchableScriptFuncOrBody<HandleCatchableError<In, InFragment, OutFragment>>or Array\Catchable error handler.
errorHandles.uncatchableScriptFuncOrBody<HandleUncatchableError<In, InFragment, OutFragment>>or Array\Uncatchable error handler.
errorHandles.exposedScriptFuncOrBody<HandleExposedUncatchableError<In, InFragment, OutFragment>>or Array\Exposed uncatchable error handler.
errorHandles.anyScriptFuncOrBody<HandleAnyError<In, InFragment, OutFragment>>or Array\Any error handler.

Merge Request

PrerequisiteBehavior
No toResponse defined, mergeRequest is trueUnbox result and merge into original request content. Make sure request content and result can be unboxed.
No toResponse defined, mergeRequest is stringUse value of mergeRequest as key, merge result into original request content. Make sure request content can be unboxed.
No toResponse defined, no mergeRequest definedReturn result directly.
With toResponse defined, mergeRequest is trueExecute toResponse first, unbox result and merge into original request content. Make sure request content and result can be unboxed.
With toResponse defined, mergeRequest is stringExecute toResponse first, use value of mergeRequest as key, merge result into original request content. Make sure request content can be unboxed.
With toResponse defined, no mergeRequest definedExecute toResponse first, return result directly.

Error Handles

Each type of error handle can be either a snippet or a set of pipeline steps. If it is defined as pipeline steps, the first step will receive the request data in the following format:

const RequestContent = {$code: errorCode, $error: error, $factor: fragment, $request: request};

Except for the first step, each subsequent step will receive request data that depends on the processing result of the previous step.

Get Property

Constructor Parameters

NameTypeDefault ValueComments
propertyNamestringSupports multi-level property names, connected by ..

The data source of given property name is after fromRequest transformation.

Delete Property

Constructor Parameters

NameTypeDefault ValueComments
propertyNamesstring or Array\

Multi-level property names is not supported, make sure the data source of given property name is after fromRequest transformation.

Snippet

Constructor Parameters

NameTypeDefault ValueComments
snippetScriptFuncOrBody\

Step Sets

Constructor Parameters

NameTypeDefault ValueComments
stepsArray\

Execute the given pipeline steps in order.

Conditional

Constructor Parameters

NameTypeDefault ValueComments
checkScriptFuncOrBody\
stepsArray\
otherwiseStepsArray\

First, execute the check snippet and return true. Then execute the given pipeline steps in order. Otherwise, execute the given otherwise pipeline steps in order.

Routes (Switch)

Constructor Parameters

NameTypeDefault ValueComments
conditionalStepsArray\
otherwiseStepsArray\

The conditional step is defined as follows:

export interface RoutesConditionalStepOptions {
	check: ScriptFuncOrBody<ConditionCheckFunc>,
	steps?: Array<PipelineStepBuilder>;
}

Execute each given condition check in order. If a condition is true, execute the corresponding pipeline steps in order. If none of the conditions are true, execute the given otherwise pipeline steps in order.

For Each

Constructor Parameters

NameTypeDefault ValueComments
originalContentNamestring$content
itemNamestring$item
stepsArray\
const RequestContent = {$code: errorCode, $error: error, $factor: fragment, $request: request};

The specified set of pipeline steps will be applied to each element of the array, and all the execution results will be gathered into an array and returned. It is important to note that the error handles of the For Each pipeline steps will be used for each iteration of executing individual elements, rather than being applied to the execution of the array as a whole. If the array is empty, the given pipeline steps will not be executed. The request data obtained in the first step of each element's execution will appear in the following format:

const RequestContent = {$content: content, $item: element, $semaphore};

If you need to terminate the loop prematurely, you just need to return the $semaphore signal from the request data. The loop will automatically end, and the collected processing results will be gathered and returned as an array.

Parallel

Constructor Parameters

NameTypeDefault ValueComments
cloneDataScriptFuncOrBody\<CloneDataFunc\<In, InFragment, EachInFragment>>Clone request data for each step.
racebooleanfalseReturns first settled result if race is true.

The specified set of pipeline steps will be executed parallel, and

  • All the execution results will be gathered into an array and returned when race is false,
  • Returns the first settled result when race is true,

It is important to note that

  • Each sub pipeline step will use the same request data, they share the same content memory address. So please be very careful NOT to attempt to modify the request data in the sub pipeline steps. Alternatively, you can use cloneData to create a copy of the request data for each sub pipeline steps, so that request data operations can be modified in certain sub pipeline steps without affecting other sub pipeline steps.
  • The error handles of the For Each pipeline step will be used for each iteration of executing individual elements, rather than being applied to the execution of the array as a whole.

Trigger Pipeline

Constructor Parameters

NameTypeDefault ValueComments
codestringPipeline code.

Execute the specified pipeline.

Trigger Pipeline Step

Constructor Parameters

NameTypeDefault ValueComments
codestringPipeline step code.

Execute the specified pipeline step.

Async

Constructor Parameters

NameTypeDefault ValueComments
stepsArray\

Execute the given pipeline steps in order, but asynchronous. Therefore, no result returned.

Database (TypeOrm) Steps

Environment Parameters

NameTypeDefault ValueComments
typeorm.DB.typestringDatabase type, mysql, better-sqlite3.
typeorm.DB.kept.on.globalbooleanKeep database instance in memory or not.

DB represents database name.

  • For mysql, default kept on global is true,
  • For Better-SQLite3, default kept on global is false.

MySQL

When typeorm.DB.type=mysql:

NameTypeDefault ValueComments
typeorm.DB.hoststringlocalhostMySQL host.
typeorm.DB.portnumber3306MySQL port.
typeorm.DB.usernamestringMySQL username.
typeorm.DB.passwordstringMySQL password.
typeorm.DB.databasestringMySQL database name.
typeorm.DB.charsetstringMySQL database charset.
typeorm.DB.timezonestringMySQL database timezone.
typeorm.DB.pool.sizenumberMySQL connection pool size.
typeorm.DB.synchronizebooleanfalse
typeorm.DB.loggingbooleanfalse
typeorm.DB.connect.timeoutnumber
typeorm.DB.acquire.timeoutnumber
typeorm.DB.insecure.authboolean
typeorm.DB.support.big.numbersbooleantrue
typeorm.DB.big.number.stringsbooleanfalse
typeorm.DB.date.stringsboolean
typeorm.DB.debugboolean
typeorm.DB.traceboolean
typeorm.DB.multiple.statementsbooleanfalse
typeorm.DB.legacy.spatial.supportboolean
typeorm.DB.timestamp.format.writestring%Y-%m-%d %H:%k:%sMySQL timestamp write format, should compatible with format.datetime, which default value is YYYY-MM-DD HH:mm:ss.
typeorm.DB.timestamp.format.readstringYYYY-MM-DD HH:mm:ssMySQL timestamp read format.

Mysql driver read DateTime column to javascript string.

PostgreSQL

When typeorm.DB.type=pgsql:

NameTypeDefault ValueComments
typeorm.DB.hoststringlocalhostPgSQL host.
typeorm.DB.portnumber5432PgSQL port.
typeorm.DB.usernamestringPgSQL username.
typeorm.DB.passwordstringPgSQL password.
typeorm.DB.databasestringPgSQL database name.
typeorm.DB.schemastringPgSQL schema name.
typeorm.DB.pool.sizenumberPgSQL connection pool size.
typeorm.DB.synchronizebooleanfalse
typeorm.DB.loggingbooleanfalse
typeorm.DB.connect.timeoutnumber
typeorm.DB.timestamp.format.writestringYYYY-MM-DD HH24:MI:SSPgSQL timestamp write format, should compatible with format.datetime, which default value is YYYY-MM-DD HH:mm:ss.
typeorm.DB.timestamp.format.readstringYYYY-MM-DDTHH:mm:ss.SSSZPgSQL timestamp read format.

PgSQL driver read DateTime column to javascript Date.

MSSQL

When typeorm.DB.type=mssql:

NameTypeDefault ValueComments
typeorm.DB.hoststringlocalhostMSSQL host.
typeorm.DB.portnumber5432MSSQL port.
typeorm.DB.usernamestringMSSQL username.
typeorm.DB.passwordstringMSSQL password.
typeorm.DB.databasestringMSSQL database name.
typeorm.DB.schemastringMSSQL schema name.
typeorm.DB.pool.sizenumberMSSQL connection pool size.
typeorm.DB.synchronizebooleanfalse
typeorm.DB.loggingbooleanfalse
typeorm.DB.authentication.typestringMSSQL authentication type.
typeorm.DB.domainstringMSSQL domain.
typeorm.DB.azure.ad.access.tokenstringMSSQL azure ad access token.
typeorm.DB.azure.ad.msi.app.service.client.idstringMSSQL azure ad msi app service client id.
typeorm.DB.azure.ad.msi.app.service.endpointstringMSSQL azure ad msi app service endpoint.
typeorm.DB.azure.ad.msi.app.service.secretstringMSSQL azure ad msi app service secret.
typeorm.DB.azure.ad.msi.vm.client.idstringMSSQL azure ad msi vm client id.
typeorm.DB.azure.ad.msi.vm.endpointstringMSSQL azure ad msi vm endpoint.
typeorm.DB.azure.ad.msi.vm.client.secretstringMSSQL azure ad msi vm client secret.
typeorm.DB.azure.ad.msi.vm.tenant.idstringMSSQL azure ad msi vm tenant id.
typeorm.DB.connect.timeoutnumber
typeorm.DB.request.timeoutnumber
typeorm.DB.pool.maxnumber5
typeorm.DB.pool.minnumber1
typeorm.DB.pool.acquire.timeoutnumber
typeorm.DB.pool.idle.timeoutnumber
typeorm.DB.instancestring
typeorm.DB.ansi.null.enabledboolean
typeorm.DB.cancel.timeoutnumber
typeorm.DB.use.utcboolean
typeorm.DB.encryptboolean
typeorm.DB.crypto.credentialsstring
typeorm.DB.tds.versionstring
typeorm.DB.arithmetic.abortboolean
typeorm.DB.trust.server.certificateboolean
typeorm.DB.timestamp.format.writestringyyyy-MM-dd hh:mm:ssMSSQL timestamp write format, should compatible with format.datetime, which default value is YYYY-MM-DD HH:mm:ss.
typeorm.DB.timestamp.format.readstringYYYY-MM-DD HH:mm:ssMSSQL timestamp read format.

MSSQL of TypeORM for more details.

MSSQL driver read DateTime column to javascript Date.

Oracle

When typeorm.DB.type=oracle:

NameTypeDefault ValueComments
typeorm.DB.hoststringlocalhostOracle host.
typeorm.DB.portnumber5432Oracle port.
typeorm.DB.usernamestringOracle username.
typeorm.DB.passwordstringOracle password.
typeorm.DB.databasestringOracle database name.
typeorm.DB.sidstringOracle database sid.
typeorm.DB.service.namestringOracle database service name.
typeorm.DB.connect.stringstringOracle connect string.
typeorm.DB.schemastringOracle schema name.
typeorm.DB.pool.sizenumberOracle connection pool size.
typeorm.DB.synchronizebooleanfalse
typeorm.DB.loggingbooleanfalse
typeorm.DB.timestamp.format.writestringYYYY-MM-DD HH24:MI:SSOracle timestamp write format, should compatible with format.datetime, which default value is YYYY-MM-DD HH:mm:ss.
typeorm.DB.timestamp.format.readstringYYYY-MM-DD HH:mm:ssOracle timestamp read format.

Oracle driver read DateTime column to javascript Date.

Better SQLite3

When typeorm.DB.type=better-sqlite3:

NameTypeDefault ValueComments
typeorm.DB.databasestring:memory:
typeorm.DB.synchronizebooleanfalse
typeorm.DB.loggingbooleanfalse

SQLite save DateTime column as javascript string.

NEVER use it in production.

Constructor Parameters

NameTypeDefault ValueComments
dataSourceNamestringDatabase name, DB.
transactionNamestringTransaction name.
autonomousbooleanfalseAutonomous transaction or not.

Autonomous transactions take precedence over the transaction name, meaning that if an autonomous transaction is enabled, the transaction specified by the transaction name will be ignored. If you need to use the transaction name, you must nest the pipeline steps within transactional step sets, and ensure that the datasource name and transaction name remain the same.

By Entity (Deprecated, not recommended)

Load Entity by ID

Constructor Parameters
NameTypeDefault ValueComments
entityNamestringTypeOrm entity name.
Request and Response
// request
export type TypeOrmIdType = string | number | bigint;
// response
export type TypeOrmEntityToLoad = Undefinable<DeepPartial<ObjectLiteral>>;

Save Entity

Constructor Parameters
NameTypeDefault ValueComments
entityNamestringTypeOrm entity name.
fillIdBySnowflakebooleanfalse
uniquenessCheckSnippetScriptFuncOrBody\
Request and Response
// request
export type EntityToSave = DeepPartial<ObjectLiteral>;
// response
export type EntityToSave = DeepPartial<ObjectLiteral>;

By SQL

Environment Parameters

NameTypeDefault ValueComments
typeorm.sql.cache.enabledbooleantrueCache parsed sql or not.

Parsed SQL will not be cached when there is one-of syntax.

Constructor Parameters

NameTypeDefault ValueComments
sqlstringSQL

Native SQL Support & Enhancement

SQL supports native database syntax. At the same time, o23/n3 enhances SQL syntax, allowing the use of the $property syntax to retrieve corresponding data from data objects, also supports multi-level property names, connected by .. For example, $person.name represents that person is an object and name is a property under person. The following are the supported syntax features:

  • IN ($...names): one-of, names should be an array,
  • LIKE $name%: starts-with,
  • LIKE $%name: ends-with,
  • LIKE $%name%: contains.

Name mapping is case-sensitive.
LIKE is case-sensitive.

Since different databases have varying degrees of support for dialects, o23/n3 also provides appropriate enhanced support for this:

  • For pagination, $.limit($offset, $limit) will be translated and executed in the appropriate dialect. For example, - MySQL uses LIMIT $offset, $limit, - PostgreSQL uses OFFSET $offset LIMIT $limit. - MSSQL and Oracle use OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY, - MSSQL requires an ORDER BY clause for pagination SQL. If there is no ORDER BY clause, will use ORDER BY 1 OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY.
  • For JSON column, because some databases (such as MSSQL) do not have a JSON column type, they cannot automatically replace strings in the result set with JSON objects, - Use config as "config.@json" to explicitly indicate that the config column is of JSON data type. - Use $config.@json to explicitly indicate that the config property of given parameters is of JSON data type.
  • For boolean column which use numeric(int/smallint/tinyint) as storage type, because some databases (such as PostgreSQL) cannot automatically convert boolean values in memory to numeric 0 or 1 in the database, - Use enabled as "enabled.@bool" to explicitly indicate that the enabled column is of boolean in-memory and numeric in database data type. - Use $enabled.@bool to explicitly indicate that the enabled property of given parameters is of boolean in-memory and numeric in database data type.
  • For datetime (MySQL, MSSQL) / timestamp (Oracle, PostgreSQL) column, - Use created_at as "createdAt.@ts" to explicitly indicate that the createdAt column is of string in-memory and timestamp in database data type. - Use $createdAt.@ts to explicitly indicate that the createdAt property of given parameters is of string in-memory and timestamp in database data type.

We recommend that if you need to consider support for multiple database dialects, using enhanced syntax will make it easier to write SQL. If you only need to support a specific database, then using its standard syntax is sufficient.

It is important to note that some databases (such as PostgreSQL) do not differentiate column names by case. This can affect the property names of the returned objects in the result set (usually recommended in camel case). Therefore, even though it is not a syntax enhancement, it is strongly recommended to use aliases to standardize the column names in the returned result set, for example, PERSON_NAME AS "personName", please pay attention to the use of quotation marks to correctly preserve the case.

Load One by SQL

Request and Response
// request
export interface TypeOrmLoadBasis extends TypeOrmBasis {
	params?: Array<TypeOrmEntityValue> | TypeOrmEntityToSave;
}

// response
export type TypeOrmEntityToLoad = Undefinable<DeepPartial<ObjectLiteral>>;

Load Many by SQL

Request and Response
// request
export interface TypeOrmLoadBasis extends TypeOrmBasis {
	params?: Array<TypeOrmEntityValue> | TypeOrmEntityToSave;
}

// response
Array<TypeOrmEntityToLoad>;

Save by SQL

Request and Response
// request
export interface TypeOrmSaveBasis extends TypeOrmBasis {
	values?: Array<TypeOrmEntityValue> | TypeOrmEntityToSave;
}

// response
export type TypeOrmIdOfInserted = TypeOrmIdType;
export type TypeOrmCountOfAffected = number;
export type TypeOrmWrittenResult = TypeOrmIdOfInserted | TypeOrmCountOfAffected;

Bulk Save by SQL

Request and Response
// request
export interface TypeOrmBulkSaveBasis extends TypeOrmBasis {
	items?: Array<Array<TypeOrmEntityValue> | TypeOrmEntityToSave>;
}

// response
export type TypeOrmIdsOfInserted = Array<TypeOrmIdOfInserted>;
export type TypeOrmCountsOfAffected = Array<TypeOrmCountOfAffected>;
export type TypeOrmBulkWrittenResult = TypeOrmIdsOfInserted | TypeOrmCountsOfAffected;

By Snippet

Constructor Parameters

NameTypeDefault ValueComments
snippetScriptFuncOrBody\

A TypeOrm Query Runner instance, $runner, will be passed to the snippet, and the snippet can use this instance to perform any operation on the database.

You do not need to manually start a transaction, whether you are using autonomous transaction or if it is nested within transaction step sets. The $runner instance passed to the snippet will automatically start a transaction.

Transactional

Transactional step sets are a wrapper for a set of pipeline steps that require the same transaction. It means that all the sub-steps inside a transactional step set can be executed within a single transaction. However, not all sub-steps within the set necessarily have to be transactional. Only the ones that need to be executed within the same transaction need to define the same transaction name as the step set. Additionally, nested transactions are also supported, which means Transactional Step Sets can be nested as well.

Steps with same datasource name and transaction name should be within same transaction.

Constructor Parameters

NameTypeDefault ValueComments
dataSourceNamestringDatasource name, DB.
transactionNamestring$default-transactionTransaction name.
stepsArray\Sub steps.

Http Steps

Fetch

Environment Parameters

NameTypeDefault ValueComments
endpoints.SYSTEM.ENDPOINT.urlstringEndpoint URL.
endpoints.SYSTEM.ENDPOINT.headersstringEndpoint request headers, use global headers if this parameter doesn't present.Format follows name=value[;name=value[...]].
endpoints.SYSTEM.global.headersstringEndpoint system global request headers.Format follows name=value[;name=value[...]].
endpoints.SYSTEM.ENDPOINT.timeoutnumberEndpoint request timeout, in seconds, use global timeout if this parameter doesn't present.
endpoints.SYSTEM.global.timeoutnumber-1Endpoint system global timeout, in seconds, -1 represents no timeout.

SYSTEM represents endpoint system, ENDPOINT represents endpoint url. For example:

CFG_ENDPOINTS_ORDER_PURCHASE_URL=https://order.com/purchase
CFG_ENDPOINTS_ORDER_PAYMENT_URL=https://order.com/payment

Constructor Parameters

NameTypeDefault ValueComments
endpointSystemCodestringEndpoint system code.
endpointNamestringEndpoint name.
urlGenerateScriptFuncOrBody\Endpoint url generator, $endpointUrl.
methodstringHttp method, default post.
timeoutnumberEndpoint timeout, in seconds.
headersGenerateScriptFuncOrBody\Endpoint request headers generator.
bodyUsedbooleanSend request with body or not, or automatically disregards the body when sending a get request when not specified.
bodyGenerateScriptFuncOrBody\Endpoint request body generator.
responseGenerateScriptFuncOrBody\Endpoint response body generator, $response.
responseErrorHandlesScriptFuncOrBody\or{key: HttpErrorCode: ScriptFuncOrBody\}Endpoint response error handlers.

Installation

Note since nestjs only support commonjs module, which means node-fetch 3 series cannot be imported since it is built on esm mode.

1.0.45

10 months ago

1.0.44

11 months ago

1.0.37

1 year ago

1.0.39

12 months ago

1.0.38

12 months ago

1.0.40

12 months ago

1.0.43

11 months ago

1.0.42

11 months ago

1.0.41

11 months ago

1.0.36

1 year ago

1.0.33

1 year ago

1.0.35

1 year ago

1.0.34

1 year ago

1.0.32

1 year ago

1.0.31

1 year ago

1.0.30

1 year ago

1.0.29

1 year ago

1.0.28

1 year ago

1.0.27

1 year ago

1.0.26

1 year ago

1.0.25

1 year ago

1.0.24

1 year ago

1.0.23

1 year ago

1.0.22

1 year ago

0.1.21

1 year ago

0.1.21-alpha.2

1 year ago

0.1.21-alpha.1

1 year ago

0.1.20

1 year ago

0.1.19

1 year ago

0.1.16

1 year ago

0.1.17

1 year ago

0.1.18

1 year ago

0.1.15

1 year ago

0.1.10

1 year ago

0.1.11

1 year ago

0.1.12

1 year ago

0.1.13

1 year ago

0.1.14

1 year ago

0.1.9

1 year ago

0.1.8

2 years ago

0.1.7

2 years ago

0.1.6

2 years ago

0.1.5

2 years ago

0.1.4

2 years ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.2-alpha.3

2 years ago

0.1.2-alpha.2

2 years ago

0.1.2-alpha

2 years ago

0.1.1

2 years ago