1+ import Ajv , { ValidateFunction } from "ajv" ;
2+ import addFormats from "ajv-formats" ;
3+
4+ import { JSONSchema7 } from "json-schema" ;
15import {
26 BadRequestError ,
37 Inflector ,
48 JSONObject ,
9+ KuzzleError ,
10+ MultipleErrorsError ,
511 NotFoundError ,
612 PluginContext ,
713} from "kuzzle" ;
@@ -31,7 +37,8 @@ export abstract class BaseProvider<T> {
3137 protected EVENT_ACCOUNT_ADD : string ;
3238 protected EVENT_ACCOUNT_REMOVE : string ;
3339
34- protected jsonSchema : JSONObject ;
40+ protected paramsJsonSchema : JSONSchema7 ;
41+ protected paramsJsonSchemaValidator : ValidateFunction ;
3542
3643 get sdk ( ) {
3744 return this . context . accessors . sdk ;
@@ -41,10 +48,14 @@ export abstract class BaseProvider<T> {
4148 return this . context . accessors . cluster ;
4249 }
4350
44- constructor ( name : string , type : ProviderType , jsonSchema : JSONObject ) {
51+ constructor ( name : string , type : ProviderType , jsonSchema : JSONSchema7 ) {
4552 this . name = name ;
4653 this . type = type ;
47- this . jsonSchema = jsonSchema ;
54+ this . paramsJsonSchema = jsonSchema ;
55+
56+ const ajv = new Ajv ( ) ;
57+ addFormats ( ajv ) ;
58+ this . paramsJsonSchemaValidator = ajv . compile ( this . paramsJsonSchema ) ;
4859
4960 this . EVENT_ACCOUNT_ADD = `${ this . name } :account:add` ;
5061 this . EVENT_ACCOUNT_REMOVE = `${ this . name } :account:remove` ;
@@ -84,8 +95,8 @@ export abstract class BaseProvider<T> {
8495 return this . name ;
8596 }
8697
87- getJsonSchema ( ) : JSONObject {
88- return this . jsonSchema ;
98+ getParamsJsonSchema ( ) : JSONSchema7 {
99+ return this . paramsJsonSchema ;
89100 }
90101
91102 abstract send (
@@ -131,6 +142,20 @@ export abstract class BaseProvider<T> {
131142 }
132143 }
133144
145+ validateParams ( params : JSONObject ) : void {
146+ const valid = this . paramsJsonSchemaValidator ( params ) ;
147+
148+ if ( valid === false ) {
149+ const errors = this . paramsJsonSchemaValidator . errors . map (
150+ ( e ) => new KuzzleError ( e . message , 400 ) ,
151+ ) ;
152+ throw new MultipleErrorsError (
153+ "Parameters does not match with the json schema defined in the provider" ,
154+ errors ,
155+ ) ;
156+ }
157+ }
158+
134159 private nodeAddAccount ( name : string , contentType : string , ...args ) {
135160 this . logInfo ( `${ Inflector . upFirst ( this . name ) } : register account "${ name } "` ) ;
136161
0 commit comments