Compare commits

...

44 Commits

Author SHA1 Message Date
e9fad241ee 1.0.49 2020-10-06 15:50:12 +00:00
34face164f fix(core): update 2020-10-06 15:50:12 +00:00
f7bf366962 1.0.48 2020-10-06 15:05:29 +00:00
046059d228 fix(core): update 2020-10-06 15:05:29 +00:00
78e8171a6a 1.0.47 2020-10-06 14:29:50 +00:00
c97a535035 fix(core): update 2020-10-06 14:29:49 +00:00
dcf198787a 1.0.46 2020-09-29 15:51:06 +00:00
a1e0ebd658 fix(core): update 2020-09-29 15:51:05 +00:00
8bf0a71266 1.0.45 2020-09-14 08:28:08 +00:00
e499612ecb fix(core): update 2020-09-14 08:28:07 +00:00
e049899599 1.0.44 2020-09-14 08:22:28 +00:00
37f4d34e7a fix(core): update 2020-09-14 08:22:27 +00:00
ca2e6895ce 1.0.43 2020-07-30 09:27:31 +00:00
ccc5c33656 fix(core): update 2020-07-30 09:27:30 +00:00
546f7f4fc7 1.0.42 2020-07-30 08:46:45 +00:00
8536060ce4 fix(core): update 2020-07-30 08:46:45 +00:00
e57c332d82 1.0.41 2020-07-26 13:48:57 +00:00
df87c6c75e fix(core): update 2020-07-26 13:48:57 +00:00
53a4375545 1.0.40 2020-07-14 16:37:45 +00:00
88022ea14b fix(core): update 2020-07-14 16:37:44 +00:00
2a681644eb 1.0.39 2020-07-14 02:20:15 +00:00
e2708c5bb3 fix(core): update 2020-07-14 02:20:15 +00:00
8c7a71ddce 1.0.38 2020-06-25 23:53:06 +00:00
5acbf420ae fix(core): update 2020-06-25 23:53:05 +00:00
5d673799cc 1.0.37 2020-06-16 22:25:20 +00:00
bb0271e021 fix(core): update 2020-06-16 22:25:20 +00:00
718feb74ae 1.0.36 2020-06-16 22:23:32 +00:00
82aa80d7d9 fix(core): update 2020-06-16 22:23:31 +00:00
67831cd37f 1.0.35 2020-06-16 22:00:39 +00:00
777817b588 fix(core): update 2020-06-16 22:00:38 +00:00
c7dd378eb3 1.0.34 2020-06-16 15:17:47 +00:00
9d9f67c91a fix(core): update 2020-06-16 15:17:46 +00:00
82cc8c29e1 1.0.33 2020-06-16 15:17:24 +00:00
625b1c6871 fix(core): update 2020-06-16 15:17:23 +00:00
e149b5a5f1 1.0.32 2020-06-16 15:03:11 +00:00
2879fb8cee fix(core): update 2020-06-16 15:03:10 +00:00
f98c2cc5e7 1.0.31 2020-06-15 16:52:56 +00:00
567845bc64 fix(core): update 2020-06-15 16:52:56 +00:00
52677ec036 1.0.30 2020-06-15 16:39:49 +00:00
8be8ce109e fix(core): update 2020-06-15 16:39:48 +00:00
6788fbf715 1.0.29 2020-06-15 16:36:54 +00:00
325e568329 fix(core): update 2020-06-15 16:36:53 +00:00
7f74fbd713 1.0.28 2020-02-12 08:29:43 +00:00
5aecb43923 fix(core): update 2020-02-12 08:29:43 +00:00
13 changed files with 9285 additions and 732 deletions

4
.gitignore vendored
View File

@ -15,8 +15,6 @@ node_modules/
# builds
dist/
dist_web/
dist_serve/
dist_ts_web/
dist_*/
# custom

View File

@ -19,22 +19,35 @@ mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
snyk:
image: registry.gitlab.com/hosttoday/ht-docker-node:snyk
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command snyk test
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- lossless
- docker
- notpriv
allow_failure: true
# ====================
# test stage
@ -49,9 +62,7 @@ testStable:
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- lossless
- docker
- priv
testBuild:
stage: test
@ -62,9 +73,7 @@ testBuild:
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- lossless
- docker
- notpriv
release:
stage: release
@ -84,6 +93,8 @@ release:
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare

View File

@ -15,7 +15,7 @@
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm"]
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}

9567
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,42 +1,48 @@
{
"name": "@apiglobal/typedrequest",
"version": "1.0.27",
"version": "1.0.49",
"private": false,
"description": "make typed requests towards apis",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild)",
"build": "(tsbuild --web && tsbundle npm)",
"format": "(gitzone format)"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.17",
"@gitzone/tstest": "^1.0.28",
"@pushrocks/smartexpress": "^3.0.57",
"@pushrocks/tapbundle": "^3.2.0",
"@types/node": "^13.7.1",
"tslint": "^6.0.0",
"@gitzone/tsbuild": "^2.1.24",
"@gitzone/tsbundle": "^1.0.72",
"@gitzone/tstest": "^1.0.43",
"@pushrocks/smartexpress": "^3.0.73",
"@pushrocks/tapbundle": "^3.2.9",
"@types/node": "^14.0.26",
"tslint": "^6.1.2",
"tslint-config-prettier": "^1.18.0"
},
"dependencies": {
"@apiglobal/typedrequest-interfaces": "^1.0.12",
"@pushrocks/lik": "^3.0.17",
"@pushrocks/smartdelay": "^2.0.6",
"@pushrocks/smartjson": "^3.0.10",
"@pushrocks/smartrequest": "^1.1.47"
"@apiglobal/typedrequest-interfaces": "^1.0.15",
"@pushrocks/isounique": "^1.0.4",
"@pushrocks/lik": "^4.0.17",
"@pushrocks/smartdelay": "^2.0.10",
"@pushrocks/smartpromise": "^3.0.6",
"@pushrocks/webrequest": "^2.0.10"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_web/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
]
}

View File

@ -8,16 +8,94 @@ make typed requests towards apis
* [docs (typedoc)](https://apiglobal.gitlab.io/typedrequest/)
## Status for master
[![pipeline status](https://gitlab.com/apiglobal/typedrequest/badges/master/pipeline.svg)](https://gitlab.com/apiglobal/typedrequest/commits/master)
[![coverage report](https://gitlab.com/apiglobal/typedrequest/badges/master/coverage.svg)](https://gitlab.com/apiglobal/typedrequest/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@apiglobal/typedrequest.svg)](https://www.npmjs.com/package/@apiglobal/typedrequest)
[![Known Vulnerabilities](https://snyk.io/test/npm/@apiglobal/typedrequest/badge.svg)](https://snyk.io/test/npm/@apiglobal/typedrequest)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/apiglobal/typedrequest/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/apiglobal/typedrequest/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@apiglobal/typedrequest)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/apiglobal/typedrequest)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@apiglobal/typedrequest)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@apiglobal/typedrequest)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@apiglobal/typedrequest)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Usage
Use TypeScript for best in class intellisense.
```typescript
import { expect, tap } from '@pushrocks/tapbundle';
import * as smartexpress from '@pushrocks/smartexpress';
import * as typedrequest from '../ts/index';
let testServer: smartexpress.Server;
let testTypedHandler: typedrequest.TypedHandler<ITestReqRes>;
// lets define an interface
interface ITestReqRes {
method: 'hi';
request: {
name: string;
};
response: {
surname: string;
};
}
tap.test('should create a typedHandler', async () => {
// lets use the interface in a TypedHandler
testTypedHandler = new typedrequest.TypedHandler<ITestReqRes>('hi', async (reqArg) => {
return {
surname: 'wow',
};
});
});
tap.test('should spawn a server to test with', async () => {
testServer = new smartexpress.Server({
cors: true,
forceSsl: false,
port: 3000,
});
});
tap.test('should define a testHandler', async () => {
const testTypedRouter = new typedrequest.TypedRouter(); // typed routers can broker typedrequests between handlers
testTypedRouter.addTypedHandler(testTypedHandler);
testServer.addRoute(
'/testroute',
new smartexpress.HandlerTypedRouter(testTypedRouter as any) // the "any" is testspecific, since smartexpress ships with its own version of typedrequest.
);
});
tap.test('should start the server', async () => {
await testServer.start();
});
tap.test('should fire a request', async () => {
const typedRequest = new typedrequest.TypedRequest<ITestReqRes>(
'http://localhost:3000/testroute',
'hi'
);
const response = await typedRequest.fire({
name: 'really',
});
console.log('this is the response:');
console.log(response);
expect(response.surname).to.equal('wow');
});
tap.test('should end the server', async () => {
await testServer.stop();
});
tap.start();
```
## Contribution

View File

@ -6,6 +6,7 @@ import * as typedrequest from '../ts/index';
let testServer: smartexpress.Server;
let testTypedHandler: typedrequest.TypedHandler<ITestReqRes>;
// lets define an interface
interface ITestReqRes {
method: 'hi';
request: {
@ -17,9 +18,10 @@ interface ITestReqRes {
}
tap.test('should create a typedHandler', async () => {
testTypedHandler = new typedrequest.TypedHandler<ITestReqRes>('hi', async reqArg => {
// lets use the interface in a TypedHandler
testTypedHandler = new typedrequest.TypedHandler<ITestReqRes>('hi', async (reqArg) => {
return {
surname: 'wow'
surname: 'wow',
};
});
});
@ -28,17 +30,16 @@ tap.test('should spawn a server to test with', async () => {
testServer = new smartexpress.Server({
cors: true,
forceSsl: false,
port: 3000
port: 3000,
});
});
tap.test('should define a testHandler', async () => {
const testTypedRouter = new typedrequest.TypedRouter(); // typed routers can broker typedrequests between handlers
testTypedRouter.addTypedHandler(testTypedHandler);
testServer.addRoute(
'/testroute',
new smartexpress.Handler('POST', async (req, res) => {
console.log(req.body);
res.json(await testTypedHandler.addResponse(req.body));
})
new smartexpress.HandlerTypedRouter(testTypedRouter as any) // the "any" is testspecific, since smartexpress ships with its own version of typedrequest.
);
});
@ -52,8 +53,9 @@ tap.test('should fire a request', async () => {
'hi'
);
const response = await typedRequest.fire({
name: 'really'
name: 'really',
});
console.log('this is the response:');
console.log(response);
expect(response.surname).to.equal('wow');
});

View File

@ -1,3 +1,4 @@
export * from './typedrequest.classes.typedrequest';
export * from './typedrequest.classes.typedhandler';
export * from './typedrequest.classes.typedrouter';
export * from './typedrequest.classes.typedresponseerror';

View File

@ -1,4 +1,5 @@
import * as plugins from './typedrequest.plugins';
import { TypedResponseError } from './typedrequest.classes.typedresponseerror';
type THandlerFunction<T extends plugins.typedRequestInterfaces.ITypedRequest> = (
requestArg: T['request']
@ -26,8 +27,28 @@ export class TypedHandler<T extends plugins.typedRequestInterfaces.ITypedRequest
'this handler has been given a wrong method to answer to. Please use a TypedRouter to filter requests'
);
}
const response = await this.handlerFunction(typedRequestArg.request);
typedRequestArg.response = response;
let typedResponseError: TypedResponseError;
const response = await this.handlerFunction(typedRequestArg.request).catch((e) => {
if (e instanceof TypedResponseError) {
typedResponseError = e;
} else {
throw e;
}
});
if (typedResponseError) {
typedRequestArg.error = {
text: typedResponseError.errorText,
data: typedResponseError.errorData,
};
}
if (response) {
typedRequestArg.response = response;
}
typedRequestArg?.correlation?.phase ? (typedRequestArg.correlation.phase = 'response') : null;
return typedRequestArg;
}
}

View File

@ -1,35 +1,110 @@
import * as plugins from './typedrequest.plugins';
import { TypedResponseError } from './typedrequest.classes.typedresponseerror';
import { TypedRouter } from './typedrequest.classes.typedrouter';
export type IPostMethod = (
typedRequestPostObject: plugins.typedRequestInterfaces.ITypedRequest
) => Promise<plugins.typedRequestInterfaces.ITypedRequest>;
export type IPostMethodWithTypedRouter = (
typedRequestPostObject: plugins.typedRequestInterfaces.ITypedRequest
) => Promise<void> | Promise<plugins.typedRequestInterfaces.ITypedRequest>;
export class TypedRequest<T extends plugins.typedRequestInterfaces.ITypedRequest> {
public urlEndPoint: string;
/**
* this typedrouter allows us to have easy async request response cycles
*/
public typedRouterRef: TypedRouter;
public webrequest = new plugins.webrequest.WebRequest();
/**
* in case we post against a url endpoint
*/
public urlEndPoint?: string;
/**
* in case we post with some other method, ec ipc communication
*/
public postMethod?: IPostMethod | IPostMethodWithTypedRouter;
public method: string;
// STATIC
constructor(urlEndPointArg: string, methodArg: T['method']) {
this.urlEndPoint = urlEndPointArg;
constructor(postEndPointArg: string | IPostMethod, methodArg: T['method']);
constructor(
postEndPointArg: string | IPostMethodWithTypedRouter,
methodArg: T['method'],
typedrouterRefArg: TypedRouter
);
constructor(
postEndPointArg: string | IPostMethodWithTypedRouter,
methodArg: T['method'],
typedrouterRefArg?: TypedRouter
) {
if (typeof postEndPointArg === 'string') {
this.urlEndPoint = postEndPointArg;
} else {
this.postMethod = postEndPointArg;
}
this.method = methodArg;
this.typedRouterRef = typedrouterRefArg;
}
/**
* firest the request
* fires the request
*/
public async fire(fireArg: T['request']): Promise<T['response']> {
const response = await plugins.smartrequest.postJson(this.urlEndPoint, {
requestBody: {
method: this.method,
request: fireArg,
response: null
const payload: plugins.typedRequestInterfaces.ITypedRequest = {
method: this.method,
request: fireArg,
response: null,
correlation: {
id: plugins.isounique.uni(),
phase: 'request',
},
};
let responseBody: plugins.typedRequestInterfaces.ITypedRequest;
if (this.urlEndPoint) {
const response = await this.webrequest.postJson(this.urlEndPoint, payload);
responseBody = response;
} else {
let responseInterest: plugins.lik.Interest<
string,
plugins.typedRequestInterfaces.ITypedRequest
>;
// having a typedrouter allows us to work with async request response cycles.
if (this.typedRouterRef) {
responseInterest = await this.typedRouterRef.fireEventInterestMap.addInterest(
payload.correlation.id,
payload
);
}
});
const responseBody: T = response.body;
const postMethodReturnValue = await this.postMethod(payload);
if (responseInterest) {
responseBody = await responseInterest.interestFullfilled;
} else if (postMethodReturnValue) {
responseBody = postMethodReturnValue;
} else {
responseBody = payload;
}
}
if (responseBody.error) {
console.log(responseBody.error.text);
console.log(responseBody.error.data);
console.error(
`Got an error ${responseBody.error.text} with data ${JSON.stringify(
responseBody.error.data
)}`
);
if (!responseBody.retry) {
throw new TypedResponseError(responseBody.error.text, responseBody.error.data);
}
return null;
}
if (responseBody.retry) {
console.log('server requested retry');
};
console.log(`server requested retry for the following reason: ${responseBody.retry.reason}`);
await plugins.smartdelay.delayFor(responseBody.retry.waitForMs);
// tslint:disable-next-line: no-return-await
return await this.fire(fireArg);
}
return responseBody.response;
}
}

View File

@ -0,0 +1,10 @@
import * as plugins from './typedrequest.plugins';
export class TypedResponseError {
public errorText: string;
public errorData: any;
constructor(errorTextArg: string, errorDataArg?: any) {
this.errorText = errorTextArg;
this.errorData = errorDataArg;
}
}

View File

@ -1,6 +1,7 @@
import * as plugins from './typedrequest.plugins';
import { TypedHandler } from './typedrequest.classes.typedhandler';
import { TypedRequest } from './typedrequest.classes.typedrequest';
/**
* A typed router decides on which typed handler to call based on the method
@ -8,41 +9,107 @@ import { TypedHandler } from './typedrequest.classes.typedhandler';
* This is thought for reusing the same url endpoint for different methods
*/
export class TypedRouter {
public handlerMap = new plugins.lik.Objectmap<
public upstreamTypedRouter: TypedRouter;
public routerMap = new plugins.lik.ObjectMap<TypedRouter>();
public handlerMap = new plugins.lik.ObjectMap<
TypedHandler<plugins.typedRequestInterfaces.ITypedRequest>
>();
public fireEventInterestMap = new plugins.lik.InterestMap<
string,
plugins.typedRequestInterfaces.ITypedRequest
>((correlationId: string) => correlationId);
/**
* adds the handler to the routing map
* @param handlerArg
* @param typedHandlerArg
*/
public addTypedHandler<T extends plugins.typedRequestInterfaces.ITypedRequest>(
handlerArg: TypedHandler<T>
typedHandlerArg: TypedHandler<T>
) {
this.handlerMap.add(handlerArg);
}
public async addResponse(typedRequest: plugins.typedRequestInterfaces.ITypedRequest) {
const typedHandler = this.handlerMap.find(handler => {
return handler.method === typedRequest.method;
});
if (!typedHandler) {
const availableMethods: string[] = [];
await this.handlerMap.forEach(async handler => {
availableMethods.push(handler.method);
});
console.log(`Cannot find method for ${typedHandler}`);
console.log(`Available methods are:`);
console.log(availableMethods);
typedRequest.error = {
text: 'There is no available method for this call on the server side',
data: {}
};
return typedRequest;
// lets check for deduplication
const existingTypedHandler = this.getTypedHandlerForMethod(typedHandlerArg.method);
if (existingTypedHandler) {
throw new Error(
`a TypedHandler for ${typedHandlerArg.method} alredy exists! Can't add another one.`
);
}
typedRequest = await typedHandler.addResponse(typedRequest);
return typedRequest;
this.handlerMap.add(typedHandlerArg);
}
/**
* adds another sub typedRouter
* @param typedRequest
*/
public addTypedRouter(typedRouterArg: TypedRouter) {
this.routerMap.add(typedRouterArg);
}
public setUpstreamTypedRouter(typedRouterArg: TypedRouter) {
this.upstreamTypedRouter = typedRouterArg;
}
public checkForTypedHandler(methodArg: string): boolean {
return !!this.getTypedHandlerForMethod(methodArg);
}
/**
* gets a typed Router from the router chain, upstream and downstream
* @param methodArg
* @param checkUpstreamRouter
*/
public getTypedHandlerForMethod(
methodArg: string,
checkUpstreamRouter = true
): TypedHandler<any> {
let typedHandler: TypedHandler<any>;
if (this.upstreamTypedRouter && checkUpstreamRouter) {
typedHandler = this.upstreamTypedRouter.getTypedHandlerForMethod(methodArg);
} else {
typedHandler = this.handlerMap.find((handler) => {
return handler.method === methodArg;
});
if (!typedHandler) {
this.routerMap.getArray().forEach((typedRouter) => {
if (!typedHandler) {
typedHandler = typedRouter.getTypedHandlerForMethod(methodArg, false);
}
});
}
}
return typedHandler;
}
/**
* if typedrequest object has correlation.phase === 'request' -> routes a typed request object to a handler
* if typedrequest object has correlation.phase === 'response' -> routes a typed request object to request fire event
* @param typedRequestArg
*/
public async routeAndAddResponse(typedRequestArg: plugins.typedRequestInterfaces.ITypedRequest) {
if (!typedRequestArg?.correlation?.phase || typedRequestArg.correlation.phase === 'request') {
const typedHandler = this.getTypedHandlerForMethod(typedRequestArg.method);
if (!typedHandler) {
console.log(`Cannot find handler for methodname ${typedRequestArg.method}`);
typedRequestArg.error = {
text: 'There is no available method for this call on the server side',
data: {},
};
return typedRequestArg;
}
typedRequestArg = await typedHandler.addResponse(typedRequestArg);
} else if (typedRequestArg.correlation.phase === 'response') {
this.fireEventInterestMap
.findInterest(typedRequestArg.correlation.id)
?.fullfillInterest(typedRequestArg);
}
return typedRequestArg;
}
}

View File

@ -4,9 +4,10 @@ import * as typedRequestInterfaces from '@apiglobal/typedrequest-interfaces';
export { typedRequestInterfaces };
// pushrocks scope
import * as isounique from '@pushrocks/isounique';
import * as lik from '@pushrocks/lik';
import * as smartdelay from '@pushrocks/smartdelay';
import * as smartrequest from '@pushrocks/smartrequest';
import * as smartjson from '@pushrocks/smartjson';
import * as smartpromise from '@pushrocks/smartpromise';
import * as webrequest from '@pushrocks/webrequest';
export { lik, smartdelay, smartrequest, smartjson };
export { isounique, lik, smartdelay, smartpromise, webrequest };