icore 0.0.37 → 1.0.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Readme.md DELETED
@@ -1,93 +0,0 @@
1
- ICore
2
- =======
3
-
4
- Проект находится в разработке. Использовать не рекомендуется!
5
-
6
- Under development. Do not use!
7
-
8
- ICore is a simple node.js framework for make an HTTP / Socket server.
9
- Idea is one base class for MVC at the component level.
10
- Implemented in the environment of the language specification ECMAScript 6 (ES6).
11
-
12
- ## Install
13
-
14
- Requires node v7.6.0 or higher for ES2015 and async-function support.
15
-
16
- ```
17
- $ npm i icore
18
- ```
19
-
20
- ## Features
21
-
22
- * Linking of async operations in a stack of promises, for building MVC logic on components.
23
- * Catch errors right in the controller.
24
- * Use ES6 strings template as a template. Write the usual CSS and HTML.
25
- * Simple REST routing using regular expressions.
26
- * It is not necessary to use the database as a database Mongo.
27
-
28
- ## API
29
-
30
- The base class ICore includes four groups of objects:
31
- * **http**: This object for creates TCP server or send request.
32
- * **tmpl**: Simple implementation of template strings as a template engine. Contains one method.
33
- * **fs**: Implements interaction with the file system.
34
- * **db**: Gear of interaction with the database Mongo.
35
-
36
- ## Example
37
-
38
- ```javascript
39
- const ICore = require('icore');
40
- global.icore = new ICore();
41
-
42
- const routes = require('./routes');
43
-
44
- icore.http.server({ host: 'localhost', port: 3000 }, inq => {
45
- inq.router()
46
- .route({
47
- method: 'GET',
48
- path: '/'
49
- },
50
- routes.index
51
- })
52
-
53
- .route({
54
- method: ['GET', 'POST'],
55
- path: '/article.*'
56
- },
57
- routes.article
58
- })
59
-
60
- .not(() => {
61
- inq.echo({ status: 400, body: 'Sorry, page not found!' });
62
- });
63
- });
64
- ```
65
-
66
- ## [RU] На русском
67
- ICore - это простой node.js фреймворк для организации HTTP/Socket сервера.
68
- Философия - один базовый класс для MVC на уровне компонентов.
69
- Реализован в среде языковой спецификации ECMAScript 6 (ES6).
70
-
71
- ## Установка
72
-
73
- Требуется node v7.6.0 и выше.
74
-
75
- ```
76
- $ npm i icore
77
- ```
78
-
79
- ## Фичи
80
-
81
- * Cвязывание асинхронных операций в стек обещаний, для построения логики на компонентах.
82
- * Отлов ошибок прямо в контроллере.
83
- * Использование ES6 строк-шаблонов в качестве шаблонизатора. Пишем обычный CSS и HTML.
84
- * Простая REST маршрутизация с применением регулярных выражений.
85
- * Нет необходимости использовать базу данных Mongo.
86
-
87
- ## API
88
-
89
- Основной класс ICore реализует четыре группы свойств-объектов:
90
- * **http**: Объект для создания TCP-сервера или отправки запросов.
91
- * **tmpl**: Простая реализация шаблонизатора на основе ES6 строк-шаблонов. Содержит всего один метод.
92
- * **fs**: Организация взаимодествия с файловой системой.
93
- * **db**: Механизм взаимодествия с MongoDB.
@@ -1,48 +0,0 @@
1
- const FS = require('fs');
2
-
3
-
4
- /*
5
- Основные функции файловой системы:
6
- - именование файлов;
7
- - программный интерфейс работы с файлами для приложений;
8
- - отображения логической модели файловой системы на физическую организацию хранилища данных;
9
- - организация устойчивости файловой системы к сбоям питания, ошибкам аппаратных и программных средств;
10
- - содержание параметров файла, необходимых для правильного его взаимодействия с другими объектами системы
11
- */
12
-
13
- class AsyncFileSystem {
14
- readDir(dirname='') {
15
- let it = (resolve, reject) => {
16
- FS.readdir(dirname, (err, data) => {
17
- if (err) {
18
- reject(err);
19
- }
20
-
21
- resolve(data);
22
- });
23
- };
24
-
25
- return new Promise(it);
26
- }
27
-
28
-
29
-
30
- readFile(filename='') {
31
- let it = (resolve, reject) => {
32
- FS.readFile(filename, 'utf8', (err, data) => {
33
- if (err) {
34
- reject(err);
35
- }
36
-
37
- resolve(data);
38
- });
39
- };
40
-
41
- return new Promise(it);
42
- }
43
- }
44
-
45
-
46
-
47
-
48
- module.exports = AsyncFileSystem;
package/src/AsyncHttp.js DELETED
@@ -1,57 +0,0 @@
1
- const HTTP = require('http');
2
- const QS = require('querystring');
3
- const { ExecutedResponse, InquiryRequest } = require('./HttpInquiry');
4
-
5
-
6
-
7
-
8
- class AsyncHttp {
9
- server(obj, it) {
10
- let srv = HTTP.createServer((...args) => {
11
- let inq = new InquiryRequest(...args);
12
- it(inq);
13
- });
14
-
15
- srv.listen(obj);
16
-
17
- return srv;
18
- }
19
-
20
-
21
-
22
- request(obj) {
23
- let it = (resolve, reject) => {
24
- if (obj.data) {
25
- obj.headers = {
26
- 'Content-Type': 'application/x-www-form-urlencoded',
27
- 'Content-Length': Buffer.byteLength(obj.data)
28
- };
29
- }
30
-
31
- if (obj.param) {
32
- obj.path += '?'+ QS.stringify(obj.param);
33
- delete obj.param;
34
- }
35
-
36
- let req = HTTP.request(obj, res => {
37
- let exe = new ExecutedResponse(res);
38
- resolve(exe);
39
- });
40
-
41
- req.on('error', reject);
42
-
43
- if (obj.data) {
44
- req.write(obj.data);
45
- }
46
-
47
- req.end();
48
- };
49
-
50
- return new Promise(it);
51
- }
52
- }
53
-
54
-
55
-
56
-
57
- module.exports = AsyncHttp;
@@ -1,87 +0,0 @@
1
- const MongoClient = require('mongodb').MongoClient;
2
-
3
-
4
-
5
-
6
- class AsyncMongoDbDriver {
7
- constructor() {
8
- this.joint;
9
- }
10
-
11
-
12
-
13
- connect(nameDB='') {
14
- let location = 'mongodb://localhost:27017/'+ nameDB;
15
-
16
- let it = (resolve, reject) => {
17
- MongoClient.connect(location, (err, joint) => {
18
- if (err) reject(err);
19
- resolve(this.joint = joint);
20
- });
21
- };
22
-
23
- return new Promise(it);
24
- }
25
-
26
-
27
-
28
- close() {
29
- this.joint.close();
30
- }
31
-
32
-
33
-
34
- use(name) {
35
- return this.joint.collection(name);
36
- }
37
-
38
-
39
-
40
- insert(name, data = {}) {
41
- let it = (resolve, reject) => {
42
- let sample = this.use(name);
43
-
44
- sample.insert(data, (err, res) => {
45
- if (err) reject(err);
46
- resolve(res);
47
- });
48
- };
49
-
50
- return new Promise(it);
51
- }
52
-
53
-
54
-
55
- find(name) {
56
- let it = (resolve, reject) => {
57
- let sample = this.use(name);
58
-
59
- sample.find().toArray((err, res) => {
60
- if (err) reject(err);
61
- resolve(res);
62
- });
63
- };
64
-
65
- return new Promise(it);
66
- }
67
-
68
-
69
-
70
- update(name, data = {}) {
71
- let it = (resolve, reject) => {
72
- let sample = this.use(name);
73
-
74
- sample.update((err, res) => {
75
- if (err) reject(err);
76
- resolve(res);
77
- });
78
- };
79
-
80
- return new Promise(it);
81
- }
82
- }
83
-
84
-
85
-
86
-
87
- module.exports = AsyncMongoDbDriver;
@@ -1,132 +0,0 @@
1
- const HttpRouter = require('./HttpRouter');
2
- const QS = require('querystring');
3
- const Cookies = require('cookies');
4
- const URL = require('url');
5
-
6
-
7
-
8
-
9
- class ExecutedResponse {
10
- constructor(res) {
11
- this.response = res;
12
- this.submerged = false;
13
-
14
-
15
- this.body = '';
16
-
17
- res.on('data', data => {
18
- this.body += data;
19
-
20
- if (this.body.length > 1e6) {
21
- res.connection.destroy();
22
- }
23
- });
24
-
25
-
26
- res.on('end', () => {
27
- this.submerged = true;
28
- });
29
- }
30
-
31
-
32
-
33
- load() {
34
- let it = (resolve, reject) => {
35
- if (this.submerged === true) {
36
- resolve(this.body);
37
- }
38
- else {
39
- this.response
40
- .on('end', () => {
41
- resolve(this.body);
42
- })
43
- .on('error', e => {
44
- reject(e);
45
- });
46
- }
47
- };
48
-
49
- return new Promise(it);
50
- }
51
- }
52
-
53
-
54
-
55
-
56
-
57
- class InquiryRequest {
58
- constructor(req, res) {
59
- this.request = req;
60
- this.response = res;
61
- this.submerged = false;
62
-
63
- this.cookies = new Cookies(req, res);
64
-
65
- this.url = URL.parse(req.url);
66
- this.paths = this.url.pathname.substr(1).split('/');
67
- this.param = QS.parse(this.url.query);
68
-
69
-
70
- this.body = '';
71
-
72
- req
73
- .on('data', data => {
74
- this.body += data;
75
-
76
- if (this.body.length > 1e6) {
77
- req.connection.destroy();
78
- }
79
- })
80
-
81
- .on('end', () => {
82
- this.submerged = true;
83
- });
84
- }
85
-
86
-
87
-
88
- router(...args) {
89
- let options = {
90
- path: this.url.pathname,
91
- method: this.request.method
92
- };
93
-
94
- return new HttpRouter(this, ...args);
95
- }
96
-
97
-
98
-
99
- load() {
100
- let it = (resolve, reject) => {
101
- if (this.submerged === true) {
102
- resolve(this.body);
103
- }
104
- else {
105
- this.request
106
- .on('end', () => {
107
- resolve(this.body);
108
- })
109
- .on('error', e => {
110
- reject(e);
111
- });
112
- }
113
- };
114
-
115
- return new Promise(it);
116
- }
117
-
118
-
119
-
120
- echo({ status=200, type='text/html', body='' }) {
121
- let res = this.response;
122
-
123
- res.writeHeader(status , { 'Content-Type': type });
124
- res.write(body);
125
- res.end();
126
- }
127
- }
128
-
129
-
130
-
131
-
132
- module.exports = { ExecutedResponse, InquiryRequest };
package/src/HttpRouter.js DELETED
@@ -1,65 +0,0 @@
1
-
2
- class HttpRouter {
3
- constructor(inquiry) {
4
- this.inquiry = inquiry;
5
- this.done = false;
6
- }
7
-
8
-
9
-
10
- route({ method, path, query }, it) {
11
- let url = this.inquiry.url;
12
- let circs = [];
13
-
14
- if (typeof method == 'string') {
15
- method = [method];
16
- }
17
-
18
- if (path) {
19
- circs.push([path, url.path]);
20
- }
21
-
22
- if (query) {
23
- circs.push([query, url.query]);
24
- }
25
-
26
-
27
- if (
28
- this.done === false
29
- &&
30
- method.some(item => {
31
- if (item == this.inquiry.request.method) {
32
- return true;
33
- }
34
- })
35
- &&
36
- circs.every(item => {
37
- let pattern = item[0].replace(/\//g, '\/');
38
- let regExp = new RegExp('^'+ pattern +'$');
39
- let res = regExp.test(item[1]);
40
-
41
- return res;
42
- })
43
- ) {
44
- this.done = true;
45
- it(this.inquiry);
46
- }
47
-
48
- return this;
49
- }
50
-
51
-
52
-
53
- not(it) {
54
- if (this.done === false) {
55
- it();
56
- }
57
-
58
- return this;
59
- }
60
- }
61
-
62
-
63
-
64
-
65
- module.exports = HttpRouter;
package/src/Templates.js DELETED
@@ -1,33 +0,0 @@
1
- const cleanSoul = str => {
2
-
3
- // Убрать служебные символы
4
- //str = str.replace(/\x0A\x0D/g, '');
5
-
6
- // Убрать спецсимволы
7
- str = str.replace(/[\t\r\n]/g, '');
8
-
9
- // Экранирование обратного апострофа
10
- str = str.replace(/`/g, '\\`');
11
-
12
- return str;
13
- };
14
-
15
-
16
-
17
-
18
- class Templates {
19
- render(patern='', inc={}) {
20
- let str = cleanSoul(patern);
21
- let keys = Object.keys(inc);
22
- let func = new Function(...keys, 'return `'+ str +'`;');
23
- let args = [];
24
-
25
- keys.forEach(key => args.push(inc[key]));
26
- str = func.apply(undefined, args);
27
-
28
- return str;
29
- }
30
- }
31
-
32
-
33
- module.exports = Templates;
package/src/index.js DELETED
@@ -1,19 +0,0 @@
1
- const AsyncMongoDbDriver = require('./AsyncMongoDbDriver');
2
- const AsyncFileSystem = require('./AsyncFileSystem');
3
- const AsyncHttp = require('./AsyncHttp');
4
- const Templates = require('./Templates');
5
-
6
-
7
-
8
-
9
- const INC = {
10
- AsyncMongoDbDriver,
11
- AsyncFileSystem,
12
- AsyncHttp,
13
- Templates
14
- };
15
-
16
-
17
-
18
-
19
- module.exports = INC;