Skip to content

Commit

Permalink
feat(p3): add p3 decorator draft
Browse files Browse the repository at this point in the history
  • Loading branch information
pismenskiy authored Mar 23, 2020
1 parent d2739fe commit aa1c00b
Show file tree
Hide file tree
Showing 19 changed files with 1,091 additions and 194 deletions.
Empty file added packages/p3/CHANGELOG.md
Empty file.
21 changes: 21 additions & 0 deletions packages/p3/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 QIWI

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
46 changes: 46 additions & 0 deletions packages/p3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# p3-json-rpc
Nestjs JSON RPC 2.0 Controller

## Install
```bash
yarn add p3-json-rpc
npm add p3-json-rpc
```

## Usage
```typescript
import {
Auth,
Client,
ClientAuth,
P3Provider, Security, SecurityLevelGuard,
SinapContext,
SinapContextValue,
TClient, TSecurity,
TSinapContext,
ClientTypeGuard,
} from '@qiwi/p3-json-rpc'
import {RpcId} from 'expressjs-json-rpc'

@P3Provider('/p3-jsonrpc/endpoint')
class CustomController {

@SecurityLevelGuard(7)
@ClientTypeGuard('client')
@SinapContext('method')
bar(
@RpcId() id: string,
@SinapContextValue() value: TSinapContext,
@Auth() auth: string,
@ClientAuth() clientAuth: string,
@Client() client: TClient,
@Security() security: TSecurity,
) {
return {id, value, auth, clientAuth, client, security}
}

}
```

## Specification
[https://www.jsonrpc.org/specification](https://www.jsonrpc.org/specification)
34 changes: 34 additions & 0 deletions packages/p3/jest.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"transform": {
"^.+\\.tsx?$": "ts-jest",
"^.+\\.jsx?$": "@swissquote/crafty-preset-jest/src/esm-transformer"
},
"collectCoverage": true,
"coveragePathIgnorePatterns": [
],
"collectCoverageFrom": [
"<rootDir>/src/main/**/*.(j|t)s"
],
"testMatch": [
"<rootDir>/src/test/js/*.js",
"<rootDir>/src/test/ts/*.ts"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"preset": "ts-jest",
"globals": {
"ts-jest": {
"tsConfig": "tsconfig.test.json"
}
}

}
105 changes: 105 additions & 0 deletions packages/p3/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
{
"name": "p3-json-rpc",
"version": "1.0.3",
"description": "P3 Controller",
"main": "target/es5/index.js",
"source": "target/ts/index.ts",
"types": "target/es5/index.d.ts",
"typescript": {
"definition": "target/es5/index.d.ts"
},
"files": [
"README.md",
"CHANGELOG.md",
"target",
"typings",
"flow-typed"
],
"scripts": {
"test": "yarn lint && yarn test:spec",
"test:gen": "yarn jest --updateSnapshot",
"test:spec": "yarn jest",
"jest": "jest -w=1 --config=jest.config.json",
"lint": "tslint -p tsconfig.test.json src/**/*.ts",
"lint:fix": "yarn lint --fix",
"clean": "rimraf target typings buildcache",
"build": "yarn build:es5 && yarn build:es6 && yarn build:ts && yarn libdef && yarn docs && yarn uglify",
"build:es5": "mkdir -p target/es5 && tsc -p tsconfig.es5.json",
"build:es6": "mkdir -p target/es6 && tsc -p tsconfig.es6.json",
"build:ts": "cp -r src/main/ts/ target/ts/",
"build:bundle": "microbundle build src/main/ts/index.ts -o target/bundle",
"dtsgen": "dts-generator --project ./ --out typings/index.d.ts --prefix p3-json-rpc/target/es5 --name p3-json-rpc --main p3-json-rpc/target/es5/index",
"flowgen": "flowgen typings/index.d.ts --output-file flow-typed/index.flow.js",
"libdef": "yarn dtsgen && yarn libdeffix && yarn flowgen",
"libdeffix": "node -r esm ../../scripts/js/libdef-fix.js --dts=./typings/index.d.ts",
"test:report": "yarn test && yarn push:report",
"push:report": "yarn coveralls:push",
"coveralls:push": "cat ./coverage/lcov.info | coveralls",
"docs": "typedoc --readme README.md --tsconfig tsconfig.json src/main --ignoreCompilerErrors || exit 0",
"uglify": "for f in $(find target -name '*.js'); do short=${f%.js}; terser -c -m -o $short.js -- $f; done",
"postupdate": "yarn && yarn build && yarn test"
},
"dependencies": {
"@nestjs/common": "^6.11.11",
"@nestjs/core": "^6.11.11",
"@qiwi/json-rpc-common": "^1.0.2",
"@qiwi/substrate": "^1.18.14",
"@types/express": "^4.17.3",
"@types/lodash": "^4.14.149",
"jsonrpc-lite": "^2.1.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^6.5.4",
"tslib": "^1.11.1"
},
"devDependencies": {
"@nestjs/platform-express": "^6.11.11",
"@nestjs/testing": "^6.11.11",
"@qiwi/semantic-release-gh-pages-plugin": "^1.15.9",
"@semantic-release/changelog": "^5.0.0",
"@semantic-release/git": "^9.0.0",
"@semantic-release/github": "^7.0.4",
"@semantic-release/npm": "^7.0.4",
"@swissquote/crafty-preset-jest": "^1.10.0",
"@types/bluebird": "^3.5.30",
"@types/jest": "^25.1.4",
"@types/jest-json-schema": "^2.1.1",
"@types/supertest": "^2.0.8",
"bluebird": "^3.7.2",
"class-transformer": "^0.2.3",
"class-validator": "^0.11.0",
"coveralls": "^3.0.9",
"dts-generator": "^3.0.0",
"eslint-plugin-typescript": "^0.14.0",
"esm": "^3.2.25",
"flowgen": "1.10.0",
"jest": "^25.1.0",
"lodash": "^4.17.15",
"microbundle": "^0.12.0-next.3",
"replace-in-file": "^5.0.2",
"rimraf": "^3.0.2",
"semantic-release": "^17.0.4",
"supertest": "^4.0.2",
"terser": "^4.6.6",
"ts-jest": "^25.2.1",
"tslint": "^6.0.0",
"tslint-config-qiwi": "^1.3.2",
"typedoc": "^0.16.11",
"typedoc-plugin-external-module-name": "^3.0.0",
"typescript": "^3.8.3",
"typescript-eslint-parser": "^22.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/qiwi/json-rpc.git"
},
"keywords": [
"json rpc",
"json-rpc"
],
"author": "Anton Golub <[email protected]>",
"license": "MIT",
"bugs": {
"url": "https://github.com/qiwi/json-rpc/issues"
},
"homepage": "https://github.com/qiwi/json-rpc#readme"
}
141 changes: 141 additions & 0 deletions packages/p3/src/main/ts/classDecorators/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import 'reflect-metadata'
import {ControllerOptions} from '@nestjs/common'
import {
Extender,
TRpcMethodParam,
IParsedObject,
parseJsonRpcObject,
JSON_RPC_METADATA,
TRpcMethodEntry,
} from '@qiwi/json-rpc-common'
import {JsonRpcController} from 'nestjs-json-rpc'
import {Request} from 'express'
import {SecurityLevel} from '../guards'
import {IMetaTypedValue} from '@qiwi/substrate'

export type TP3Meta = {
securityLevel?: number
clientType?: Array<string>
}
export type TP3RpcMethodEntry = TRpcMethodEntry & { meta: TP3Meta }

export type TSinapMeta = {
auth?: string
clientAuth?: string | string[]
client?: {
clientType: string
clientId?: string
}
security?: {
level: number
}
}

type IP3MetaTypedValue = IMetaTypedValue<IParsedObject, 'jsonRpcP3', TSinapMeta>

export const P3Provider = (path: ControllerOptions | string): ClassDecorator => {
return <TFunction extends Function> (target: TFunction) => {
const extend: Extender = base => {
@JsonRpcController(path)
class JsonRpcBase extends base {}

class Extended extends JsonRpcBase {

static resolveParam(boxedP3JsonRpc: IP3MetaTypedValue, Param: any, {type}: TRpcMethodParam) {
if (boxedP3JsonRpc.value.type !== 'request') {
return
}

const {value, meta} = boxedP3JsonRpc
const paramMap = {
// @ts-ignore
locale: value.payload.params?.locale,
// @ts-ignore
query: value.payload.params?.query,
// @ts-ignore
fields: value.payload.params?.fields,
id: value.payload.id,
client: meta.client,
security: meta.security,
auth: meta.auth,
clientAuth: meta.clientAuth,
}

// @ts-ignore
const data = paramMap[type]

return typeof Param === 'function' ? new Param(data) : data
}

static parseRequest(req: Request): IP3MetaTypedValue | undefined {
// @ts-ignore
const jsonRpc = parseJsonRpcObject(req.body)

if (Array.isArray(jsonRpc)) {
// TODO
throw new Error('unexpected error')
}

if (req.body.client.clientType === undefined || req.body.security.level === undefined) {
throw new Error('unexpected error')
}

return {
meta: {
client: req.body.client,
security: req.body.security,
auth: req.get('authorization'),
clientAuth: req.get('client-authorization'),
},
value: jsonRpc,
type: 'jsonRpcP3',
}
}

static resolveHandler(instance: Extended, boxedJsonRpc: IP3MetaTypedValue): {handler: Function, params: any[]} | {[key: string]: any} {
// @ts-ignore
const _method = boxedJsonRpc.value.payload.method

const meta = Reflect.getMetadata(JSON_RPC_METADATA, this) || {}
const methodMeta: TP3RpcMethodEntry | undefined = (Object as any).values(meta)
.find(({method, meta}: TP3RpcMethodEntry) => {
if (_method !== method) {
return
}

if ((meta?.securityLevel ?? SecurityLevel.INSECURE) > boxedJsonRpc.meta.security?.level!) {
return
}

if (meta?.clientType !== undefined && !(meta?.clientType.includes(boxedJsonRpc.meta.client?.clientType!))) {
return
}

return true
})

if (!methodMeta) {
return {}
}

const propKey = methodMeta.key + ''
const handler = this.prototype[propKey]
const paramTypes = Reflect.getMetadata('design:paramtypes', instance, propKey)
const params = (methodMeta.params || []).map((param: TRpcMethodParam, index: number) => {
return this.resolveParam(boxedJsonRpc, paramTypes[index], param)
})

return {
params,
handler,
}
}

}

return Extended
}

return extend(target as any)
}
}
Loading

0 comments on commit aa1c00b

Please sign in to comment.