From f6ca92bc8e61d9e8bfa5317642f7e757af21ecc8 Mon Sep 17 00:00:00 2001 From: Nikiroy78 Date: Thu, 13 Oct 2022 11:42:58 +0300 Subject: [PATCH] add files into repos --- .gitignore | 3 ++- codeExample.js | 26 ++++++++++++++++++++++---- components/Group.js | 6 +++++- components/Main.js | 19 ++++++++++++++++++- components/Method.js | 31 +++++++++++++------------------ components/types.js | 38 ++++++++++++++++++++++++++++++++++++-- 6 files changed, 96 insertions(+), 27 deletions(-) diff --git a/.gitignore b/.gitignore index b512c09..17ec4ac 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -node_modules \ No newline at end of file +node_modules +*.npe \ No newline at end of file diff --git a/codeExample.js b/codeExample.js index 166a529..b551ed3 100644 --- a/codeExample.js +++ b/codeExample.js @@ -2,11 +2,11 @@ const backend = require('./index'); // Создаём класс бэкенда, наследующий класс backend.Main class Main extends backend.Main { - session (params, sessionData) { // Настраиваем сессию (опционально) + session (params, sessionData, next) { // Настраиваем сессию (опционально) sessionData._setValue('example', 1); // Задать значение console.log(sessionData.example); // Получить значение из сессии sessionData._remove('example'); // Убрать значение - return 1; // Успешно + return next(); // Успешно return 'Example error'; // Пример ошибки }; @@ -22,6 +22,14 @@ class Main extends backend.Main { code: 400 }};*/ + session (params, sessionData) { + sessionData._setValue('example', 1); // Задать значение + console.log(sessionData.example); // Получить значение из сессии + sessionData._remove('example'); // Убрать значение + return 1; // Успешно + return 'Example error' // Пример ошибки + } + responseHandler (response) { return ({ mainbody : { response }, headers : { @@ -38,11 +46,20 @@ class Main extends backend.Main { var server = new Main( false // Отобразить в заголовках информацию о текущем фреймворке ); +server.setSessionParams( // Зададим необходимые параметры для сессии + { + session_id : { + required : true, + type : backend.types.integer, + values : [1] + } + } +); server.typeError = 'param {param} must be only {long_type} ({short_type})'; // Создаём класс группы методов class ExampleMethodGroup extends backend.Group { - handler (params, session) { // Путевая обработка + handler (params, session) { // Путевая обработка session._setValue('example', 1); // Задать значение console.log(session.example); // Получить значение из сессии session._remove('example'); // Убрать значение @@ -62,7 +79,8 @@ class ExampleMethod extends backend.Method { text : params.text, result : this.MainObject.call('sum', { a : 15, - b : 17 + b : 17, + session_id : params.session_id }) }; throw new backend.ApiError('EXAMPLE_ERROR', new Object()); diff --git a/components/Group.js b/components/Group.js index 8a25734..0c19b1f 100644 --- a/components/Group.js +++ b/components/Group.js @@ -1,4 +1,8 @@ -class Group {} +class Group { + constructor () { + + } +} module.exports = Group; \ No newline at end of file diff --git a/components/Main.js b/components/Main.js index 5c0c0b0..8482db1 100644 --- a/components/Main.js +++ b/components/Main.js @@ -17,6 +17,13 @@ class Main { constructor (sendHeaders = true) { this.sendHeaders = sendHeaders; this.methods = new Object(); + this.sessionData = new Object(); + + this.fileUploadConfig = { + limits: { fileSize : 1024 * 1024 * 256 }, // 256 Mb maximum + abortOnLimit: true, + responseOnLimit: '{"error":"FILE_SIZE_LIMIT_HAS_BEEN_REACHED"}' + }; } paramsError (required, additional) { @@ -46,6 +53,10 @@ class Main { } } + setSessionParams (sessionParams) { + this.sessionData = sessionParams; + } + session (params, sessionData) { return 1; } responseHandler (result) { return ({ @@ -64,6 +75,10 @@ class Main { call (method, params) { return this.methods[method].pre_execute(params); } + + fileSetting (fileUploadConfig) { + this.fileUploadConfig = fileUploadConfig; + } router (returnMiddlewareFunction = false, middlewareFunction = (req, res, next) => next(), debug = (text) => console.log(text)) { let router = express.Router(); @@ -73,7 +88,9 @@ class Main { // parse some custom thing into a Buffer router.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) // parse an HTML body into a string - router.use(bodyParser.text({ type: 'text/html' })) + router.use(bodyParser.text({ type: 'text/html' })); + // parse files + app.use(require('express-fileupload')(this.fileUploadConfig)); for (let name in this.methods) { debug(`CONNECT METHOD : ${name}`); diff --git a/components/Method.js b/components/Method.js index 863ce95..4bd0702 100644 --- a/components/Method.js +++ b/components/Method.js @@ -78,26 +78,14 @@ class Method { files, cookies ) { - // Execute session - let sessionObject = new Session(); - this.MainObject.session(compileParams({ - headers, - json, - params, - query, - body, - files, - cookies - }), sessionObject); - let values = sessionObject._getValues(); - for (let key in values) { paramsEndless[key] = values[key]; } - let paramsEndless = new Object(); let paramScheme; let required = { missed : [], unsyntax : [] }; let additional = { missed : [], unsyntax : [] }; let checkKeys; - for (let param in this.paramsCompiles) { + let paramsCompiles = Object.assign({}, this.paramsCompiles, this.MainObject.sessionData); + + for (let param in paramsCompiles) { checkKeys = new Array(); paramScheme = { required : false, @@ -107,7 +95,7 @@ class Method { allow_params : ['headers', 'json', 'params', 'query', 'body', 'files', 'cookies'] }; // Configure paramScheme - for (let key in this.paramsCompiles[param]) { paramScheme[key] = this.paramsCompiles[param][key]; } + for (let key in paramsCompiles[param]) { paramScheme[key] = paramsCompiles[param][key]; } // check missible if (headers[param] != undefined & paramScheme.allow_params.indexOf('headers') != -1) { checkKeys.push('headers'); } if (json[param] != undefined & paramScheme.allow_params.indexOf('json') != -1) { checkKeys.push('json'); } @@ -183,8 +171,9 @@ class Method { let isSyntax; let value; let paramScheme; + let paramsCompiles = Object.assign(this.paramsCompiles, this.MainObject.sessionData); - for (let param in this.paramsCompiles) { + for (let param in paramsCompiles) { paramScheme = { required : false, type : this.isDynamic ? typesApi.dynamic : typesApi.unknown, @@ -192,7 +181,7 @@ class Method { conversion : false, allow_params : ['headers', 'json', 'params', 'query', 'body', 'files', 'cookies'] }; - for (let key in this.paramsCompiles[param]) { paramScheme[key] = this.paramsCompiles[param][key]; } + for (let key in paramsCompiles[param]) { paramScheme[key] = paramsCompiles[param][key]; } if (params[param] === undefined) { if (paramScheme.required) { required.missed.push(param); @@ -233,6 +222,12 @@ class Method { throw this.MainObject.paramsError(required, additional); } } + // Исполнение сессии + let sessionData = new Session(); + this.MainObject.session(params, sessionData); + sessionData = sessionData._getValues(); + for (let key in sessionData) { params[key] = sessionData[key]; } + // Исполнение группы return this.execute(params); } diff --git a/components/types.js b/components/types.js index e7f3cf1..88f264a 100644 --- a/components/types.js +++ b/components/types.js @@ -1,4 +1,4 @@ -module.exports = { +const types = { dynamic : { long_name : 'dynamic', short_name : 'dyn', @@ -62,6 +62,37 @@ module.exports = { } } }, + file : (allowed_types=null) => ({ + long_name : 'file', + short_name : 'file', + checkSchema : (value, schema) => { + if (schema.min_length != undefined) { // min_length + if (value.size < schema.min_length) { + return [false, 'minLengthError']; + } + } + + if (schema.max_length != undefined) { // max_length + if (value.size > schema.max_length) { + return [false, 'maxLengthError']; + } + } + + if (allowed_types != null) { + let file_extension = value.name.split(".")[value.name.split(".").length - 1]; + if (allowed_types.indexOf(file_extension.toLowerCase()) == -1) { + return [false, 'unAllowExtension']; + } + } + + return [true, 'ok']; + }, + syntax : (value, needs_convert = false) => { + if (typeof(value) != 'object') { + return [false, undefined]; + } + } + }), string : { long_name : 'string', short_name : 'str', @@ -98,4 +129,7 @@ module.exports = { } } } -} \ No newline at end of file +}; + + +module.exports = types; \ No newline at end of file