beech-api 3.8.0 → 3.9.75

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.
Files changed (59) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1715 -1244
  3. package/index.js +2 -2
  4. package/package.json +92 -83
  5. package/packages/cli/beech +9 -10
  6. package/packages/cli/bin/beech-app.js +389 -389
  7. package/packages/cli/bin/beech-service.js +262 -132
  8. package/packages/cli/core/auth/Credentials.js +174 -147
  9. package/packages/cli/core/auth/Passport.js +664 -592
  10. package/packages/cli/core/auth/_Request.js +12 -12
  11. package/packages/cli/core/configure/_gitignore +16 -15
  12. package/packages/cli/core/configure/_sequelizerc +9 -9
  13. package/packages/cli/core/configure/app.config-basic.js +55 -55
  14. package/packages/cli/core/configure/app.config-sequelize.js +88 -88
  15. package/packages/cli/core/configure/beech.config.js +9 -9
  16. package/packages/cli/core/configure/global.config-basic.js +8 -8
  17. package/packages/cli/core/configure/global.config-sequelize.js +8 -8
  18. package/packages/cli/core/configure/jest.config.js +6 -6
  19. package/packages/cli/core/configure/jsconfig.json +8 -7
  20. package/packages/cli/core/configure/passport.config.js +97 -97
  21. package/packages/cli/core/databases/mysql.js +94 -95
  22. package/packages/cli/core/databases/sequelize.js +187 -179
  23. package/packages/cli/core/databases/test.js +251 -170
  24. package/packages/cli/core/file-walk/file-walk.js +35 -35
  25. package/packages/cli/core/generator/_endpoints +15 -15
  26. package/packages/cli/core/generator/_endpoints_basic +42 -42
  27. package/packages/cli/core/generator/_help +26 -18
  28. package/packages/cli/core/generator/_help_create +10 -10
  29. package/packages/cli/core/generator/_help_service +10 -10
  30. package/packages/cli/core/generator/_helpers +9 -9
  31. package/packages/cli/core/generator/_helpers_basic +22 -22
  32. package/packages/cli/core/generator/_models +6 -29
  33. package/packages/cli/core/generator/_models_basic +13 -22
  34. package/packages/cli/core/generator/_package +23 -20
  35. package/packages/cli/core/generator/_scheduler +32 -22
  36. package/packages/cli/core/generator/_spec +29 -29
  37. package/packages/cli/core/generator/index.js +1081 -738
  38. package/packages/cli/core/helpers/2fa.js +106 -85
  39. package/packages/cli/core/helpers/math.js +115 -103
  40. package/packages/cli/core/helpers/poolEntity.js +103 -59
  41. package/packages/cli/core/index.js +264 -188
  42. package/packages/cli/core/middleware/express/duplicateRequest.js +16 -12
  43. package/packages/cli/core/middleware/express/jwtCheckAllow.js +86 -68
  44. package/packages/cli/core/middleware/express/rateLimit.js +29 -17
  45. package/packages/cli/core/middleware/express/slowDown.js +2 -2
  46. package/packages/cli/core/middleware/index.js +6 -6
  47. package/packages/cli/core/middleware/origin/guard/advance.js +75 -74
  48. package/packages/cli/core/middleware/origin/whitelist/cors.js +94 -94
  49. package/packages/cli/core/services/http.express.js +481 -441
  50. package/packages/cli/core/test/check-node.js +21 -0
  51. package/packages/cli/core/test/utils.js +7 -7
  52. package/packages/cli/entry +10 -0
  53. package/packages/lib/index.js +6 -6
  54. package/packages/lib/src/endpoint.js +947 -532
  55. package/packages/lib/src/guard.js +60 -60
  56. package/packages/lib/src/salt.js +3 -3
  57. package/packages/lib/src/schema.js +96 -93
  58. package/packages/lib/src/specificExpress.js +7 -7
  59. package/packages/lib/src/user.js +271 -271
package/README.md CHANGED
@@ -1,1244 +1,1715 @@
1
- [![N|Solid](https://i.ibb.co/NKxx9NQ/beech320.jpg)](https://github.com/bombkiml)
2
-
3
- # Beech API framework
4
- #### Stable v.3.8.0 (LTS)
5
-
6
- [![beech-api release](https://img.shields.io/github/v/release/bombkiml/beech-api)](https://github.com/bombkiml/beech-api/releases/tag/3.8.0)
7
- [![PyPI license](https://shields.io/pypi/l/ansicolortags.svg)](https://github.com/bombkiml/beech-api/blob/master/README.md)
8
-
9
- # What is Beech API ?
10
-
11
- The Beech API is API framework, It's help you with very easy to create API project under [Node.js](https://nodejs.org)
12
-
13
- # Environment
14
-
15
- - [`Node.js`](https://nodejs.org) >= 14.19.0+ (recommended)
16
-
17
- # Installation
18
-
19
- Beech API requires Node.js version 14.19.0 or above. You can manage multiple versions of Node on the same machine with [nvm](https://github.com/creationix/nvm) or [nvm-windows](https://github.com/coreybutler/nvm-windows). So, Let's go to install `beech-api`
20
-
21
- ```sh
22
- # NPM
23
- $ npm install beech-api --global
24
-
25
- # Yarn
26
- $ yarn global add beech-api
27
- ```
28
-
29
- Installation demo:
30
-
31
- [Demo](https://i.ibb.co/hySFxy3/install-beech720-1.gif)
32
- ![Alt Text](https://i.ibb.co/hySFxy3/install-beech720-1.gif)
33
-
34
- After installation, you will have access to the `beech-app` binary in your command line.
35
- You can check you have the right version with this command:
36
-
37
- ```sh
38
- $ beech-app --version
39
- ```
40
-
41
- # Creating a project
42
-
43
- Create a new project run:
44
-
45
- ```sh
46
- $ beech-app create hello-world
47
- ```
48
- Run your project:
49
- ```sh
50
- $ cd hello-world
51
-
52
- $ npm start
53
- # OR
54
- $ yarn start
55
- ```
56
-
57
- **Note:** The Beech API it's start server at [http://localhost:9000](http://localhost:9000) you can change new a port in `app.config.js` file.
58
-
59
-
60
- # Upgrade to latest version
61
- The Beech API upgrade to latest version command avariable :
62
-
63
- ```sh
64
- // Project upgrade
65
- $ beech-app update
66
-
67
- // Global upgrade
68
- $ beech-app update -g, --global
69
- ```
70
-
71
- # Beech CLI tool available
72
- After installation, you will have access to the `beech` binary in your command line.
73
- The `beech` command has a number of options and you can explore them all by running:
74
-
75
- ```sh
76
- $ beech --help
77
- ```
78
-
79
- The `beech` command line available:
80
-
81
- ```
82
- Usage:
83
- $ beech [options] [arguments] [special]
84
-
85
- Options:
86
- ?, -h, --help Display this help message.
87
- -v, --version Display the application version.
88
-
89
- The following commands are available:
90
-
91
- $ beech make <endpoint> Create a new Endpoints and unit test file,
92
- You might using [special] `-R, --require`
93
- for choose Model(s) used to endpoint file.
94
- $ beech make <model> -M, --model Create a new Models file.
95
- $ beech make <helper> --helper Create a new Helpers file.
96
- $ beech passport init Initialize authentication with passport-jwt.
97
- $ beech skd init Initialize Job Scheduler file.
98
- $ beech key:generate, key:gen Re-Generate application key (Dangerous!).
99
- $ beech hash:<text> Hash text for Access to Database connection.
100
- ```
101
- ❓ **Note:** Every to create new project will be generated new ``app_key`` in ``app.config.js`` file, If you can re-generate. Can use command ``$ beech key:generate`` or ``$ beech key:gen``
102
-
103
- # Database connection
104
-
105
- You might connection to Database with `database_config` object in `app.config.js` file. Anything can support to multiple Database connections.
106
-
107
- The connection base on `pool_base` in `global.config.js` file.
108
-
109
- - `basic` = Support only Raw Query with Only MySQL.
110
- - `sequelize` = Support PDO, Raw Query with various Database Engine.
111
-
112
- In case Access to Database must to Hash the `username` and `password` with Beech CLI like this.
113
-
114
- ```sh
115
- // Hash database username
116
- $ beech hash:root
117
- Output: m42BVxQ6Q4kLdRX7xS_Hm7WbQiNqShJDvw9SLCgI431oafWBtQJoJDnoCL
118
-
119
- // Hash database password
120
- $ beech hash:password
121
- Output: FjgcgJPylkV7EeQJjea_EeifPwaHVO9onD3ATk3YYAyvjtMGu3dcDS0ejA
122
-
123
- ```
124
- Example:
125
-
126
- 📂 app.config.js
127
- ```js
128
- // basic & sequelize (needed Hash)
129
-
130
- ...
131
-
132
- database_config: [
133
- {
134
- dialect: "mysql",
135
- name: "mysql_my_store_db",
136
- host: "localhost",
137
- username: "m42BVxQ6Q4kLdRX7xS_Hm7WbQiNqShJDvw9SLCgI431oafWBtQJoJDnoCL",
138
- password: "FjgcgJPylkV7EeQJjea_EeifPwaHVO9onD3ATk3YYAyvjtMGu3dcDS0ejA",
139
- database: "my_store_db",
140
- port: "3306",
141
-
142
- // Specify global options, which are used when Define is called.
143
- define: {
144
- charset: "utf8",
145
- freezeTableName: true,
146
- ...
147
- },
148
-
149
- timezone: "+07:00", // Example: GMT+2
150
- // or use a named timezone supported by Intl.Locale
151
- // timezone: 'America/Los_Angeles',
152
-
153
- logging: console.log, // SQL trace logs
154
-
155
- is_connect: true, // boolean, Turn ON/OFF to connect
156
- },
157
-
158
- ...
159
-
160
- ],
161
-
162
- ...
163
- ```
164
- ❓ **Caution! :** Every re-new generate `app_key`. Must to new Hash your Access and change to ALL Database connections.
165
-
166
- # Part of generate file
167
-
168
- ## # Generate Endpoints
169
-
170
- The `endpoints` keep the endpoints basic request files currently support `GET`, `POST`, `PUT`, `PATCH` and `DELETE`.
171
-
172
- So, you might create new endpoints with constant `endpoint` object variable in `src/endpoints/` folder and file neme must be end with `-endpoints.js`
173
-
174
- ```sh
175
- $ beech make endpointName
176
- ```
177
- You might using [special] `-R, --require` for choose Model(s) used for that endpoint.
178
-
179
- ### Example ***(Basic)*** : Fruit endpoints.
180
-
181
- 📂 fruit-endpoints.js
182
- ```js
183
- exports.init = () => {
184
-
185
- // GET method
186
- endpoint.get("/fruit", Credentials, (req, res) => {
187
- // @response
188
- res.json({
189
- code: 200,
190
- status: "SUCCESS",
191
- message: "GET /fruit request.",
192
- });
193
- });
194
-
195
-
196
- // POST method
197
- endpoint.post("/fruit", Credentials, (req, res) => {
198
- // @response
199
- res.json({
200
- code: 200,
201
- status: "SUCCESS",
202
- message: "POST request at /fruit",
203
- result: {
204
- id: req.body.id,
205
- name: req.body.name,
206
- },
207
- });
208
- });
209
-
210
-
211
- // PUT method
212
- endpoint.put("/fruit/:id", Credentials, (req, res) => {
213
- // @response
214
- res.json({
215
- code: 200,
216
- status: "SUCCESS",
217
- message: "PUT request at /fruit/" + req.params.id,
218
- });
219
- });
220
-
221
-
222
- // DELETE method
223
- endpoint.delete("/fruit/:id", Credentials, (req, res) => {
224
- // @response
225
- res.json({
226
- code: 200,
227
- status: "SUCCESS",
228
- message: "DELETE request at /fruit/" + req.params.id,
229
- });
230
- });
231
-
232
- ...
233
-
234
- }
235
- ```
236
-
237
- ### Example ***(Sequelize)*** : Fruit endpoints.
238
-
239
- 📂 fruit-endpoints.js
240
- ```js
241
- // Require Model schema, Function & Others
242
- const { Fruit } = require("@/models/Fruit");
243
-
244
- exports.init = () => {
245
-
246
- // GET method
247
- endpoint.get('/fruit', async (req, res) => {
248
- // example call Fruit model for get data
249
- res.json({
250
- code: 200,
251
- status: "SUCCESS",
252
- results: await Fruit.findAll();
253
- });
254
- });
255
-
256
- ...
257
-
258
- }
259
- ```
260
-
261
-
262
- ## # Generate Models ###
263
-
264
- The `models` keep the files of function(s) data managemnets for Retriving, Creating, Updating and Destroying (CRUD). for understanding you might make model name same your table name inside `src/models` folder.
265
-
266
- ```sh
267
- $ beech make modelName --model
268
- ```
269
-
270
- ### Example ***(Basic)*** : Fruit model.
271
-
272
- 📂 Fruit.js
273
- ```js
274
- module.exports = {
275
-
276
- // Example basic function get data
277
- getData() {
278
-
279
- return {
280
- id: 1,
281
- name: "John Doe",
282
- }
283
-
284
- },
285
-
286
- // Example basic function get data from MySQL table
287
- getFruit() {
288
-
289
- // calling Pool connection name by `mysql.default_db`
290
- mysql.default_db.query("SELECT * FROM fruit", (err, results) => {
291
-
292
- if (err) { throw err }
293
- return results;
294
-
295
- });
296
-
297
- }
298
-
299
- };
300
- ```
301
-
302
- ### Example ***(Sequelize)*** : Fruit model.
303
-
304
- You can asign more DataTypes, Learn more : [Sequelize docs](https://sequelize.org/docs/v6/core-concepts/model-basics/#data-types)
305
-
306
- 📂Fruit.js
307
- ```js
308
- const { Schema } = require("beech-api");
309
-
310
- // Define table Schema with `Schema(sql.default_db)` connection name
311
- const Fruit = Schema(sql.default_db).define("fruit", {
312
- fruit_id: {
313
- field: "id", // Rename PK field to fruit_id Ref: `id` field in fruit table
314
- type: DataTypes.INTEGER,
315
- autoIncrement: true,
316
- primaryKey: true
317
- },
318
- friut_uuid: {
319
- field: "uuid",
320
- type: DataTypes.STRING(100),
321
- allowNull: true,
322
- defaultValue: DataTypes.UUIDV4,
323
- },
324
- fruitName: DataTypes.STRING,
325
- fruitQty: DataTypes.INTEGER,
326
- fruitPrice: {
327
- type: DataTypes.INTEGER,
328
- allowNull: false, // Allow null feilds
329
- },
330
- createdAt: {
331
- type: DataTypes.DATE,
332
- allowNull: false,
333
- defaultValue: DataTypes.NOW,
334
- },
335
- updatedAt: {
336
- type: DataTypes.DATE,
337
- allowNull: true,
338
- },
339
- }, {
340
- // Enables timestamps with createdAt and updatedAt
341
- timestamps: true,
342
- // Custom field names createdAt and updatedAt
343
- createdAt: "createdAt",
344
- updatedAt: "updatedAt",
345
- });
346
-
347
- Fruit.options = {
348
- // Choose one for Allow magic generate default Endpoint (CRUD), It's like magic creating The endpoints for you (CRUD) ✨
349
-
350
- // Option 1: Allow all methods
351
- defaultEndpoint: true,
352
-
353
- // Option 2: Allow with specific per methods
354
- defaultEndpoint: {
355
- GET: true,
356
- POST: false,
357
- PATCH: {
358
- allow: true, // allow Auto-Endpoint
359
- jwt: {
360
- allow: true, // allow JWT
361
- broken_role: [
362
- { role: [1, 2] },
363
- ],
364
- },
365
- },
366
- DELETE: false,
367
- },
368
-
369
- limitRows: 100, // Limit rows default 100
370
-
371
- };
372
-
373
- // Example Finder by id (ORM), Learn more: https://sequelize.org/docs/v6/core-concepts/model-querying-finders/
374
- function exampleFindOneFruitById(id) {
375
- return Fruit.findOne({ where: { id: id } });
376
- }
377
-
378
-
379
- // Example Raw Query with Model Instances. This allows you to easily map a query to a predefined model
380
- function exampleGetAllFruitWithModelInstance(id) {
381
- return Fruit.query("SELECT * FROM fruit", {
382
- model: Fruit, // When JOIN table needed register that table [Fruit, ...]
383
- mapToModel: true // pass true here if you have any mapped fields
384
- });
385
- }
386
-
387
- // Example Raw Query, Learn more: https://sequelize.org/docs/v6/core-concepts/raw-queries/
388
- function exampleGetAllFruit(id) {
389
- return Fruit.query("SELECT * FROM fruit");
390
- }
391
-
392
- ...
393
-
394
- // Export Schema, Function, ...
395
- module.exports = {
396
- Fruit,
397
- exampleFindOneFruitById,
398
- exampleGetAllFruitWithModelInstance,
399
- exampleGetAllFruit,
400
- ...
401
- };
402
- ```
403
- #### That's cool! It's like magic creating The endpoints for you (CRUD) ✨
404
-
405
- Now! you can request to `/fruit` with methods GET, POST, PATCH and DELETE like this.
406
-
407
- | Efficacy | Method | Endpoint | Body |
408
- |:---------|:---------|:-----------------------|:-----------|
409
- | Create | POST | /fruit | { } |
410
- | Read | GET | /fruit | No |
411
- | Read | GET | /fruit/:id | No |
412
- | Read | GET | /fruit/:limit/:offset | No |
413
- | Update | PATCH | /fruit/:id | { } |
414
- | Delete | DELETE | /fruit/:id | No |
415
-
416
- ## # Transactions
417
-
418
- Sequelize does not use transactions by default. However, for production-ready usage of Sequelize, you should definitely configure Sequelize to use transactions.
419
-
420
- Beech use Sequelize supports three ways of using transactions:
421
-
422
- - ### Way 1 - Disorganized transactions :
423
- ```js
424
- // First, we start a transaction from your connection and save it into a variable
425
- const t = await Fruit.transaction();
426
-
427
- try {
428
-
429
- // Then, we do some calls passing this transaction as an option:
430
- const fruit = await Fruit.create({ fruitName: 'Banana', fruitQty: '5', }, { transaction: t });
431
- await fruit.addSibling({ fruitName: 'Litle', fruitQty: '2', }, { transaction: t }); // Error function
432
-
433
- // If the execution reaches this line, no errors were thrown.
434
- // We commit the transaction.
435
- await t.commit();
436
-
437
- } catch (error) {
438
-
439
- // If the execution reaches this line, an error was thrown.
440
- // We rollback the transaction.
441
- await t.rollback();
442
-
443
- }
444
- ```
445
-
446
- - ### Way 2 - Organized transactions :
447
- ```js
448
- // First, we start a transaction from your connection and save it into a variable
449
- Fruit.transaction(async t => {
450
- try {
451
-
452
- // Then, we do some calls passing this transaction as an option:
453
- const fruit = await Fruit.create({ fruitName: 'Banana', fruitQty: '5', }, { transaction: t });
454
- await fruit.addSibling({ fruitName: 'Litle', fruitQty: '2', }, { transaction: t }); // Error function
455
-
456
- // If the execution reaches this line, no errors were thrown.
457
- // We commit the transaction.
458
- await t.commit();
459
-
460
- } catch (error) {
461
-
462
- // If the execution reaches this line, an error was thrown.
463
- // We rollback the transaction.
464
- await t.rollback();
465
-
466
- }
467
- });
468
- ```
469
-
470
- - ### Way 3 - Transactions set Isolation levels :
471
-
472
- The possible [isolations levels](https://sequelize.org/docs/v6/other-topics/transactions/#isolation-levels) to use when starting a transaction:
473
-
474
- ```js
475
- const { Transaction } = require('sequelize');
476
-
477
- // First, we start a transaction from your connection and save it into a variable
478
- Fruit.transaction(
479
- {
480
- isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,
481
- },
482
- async t => {
483
- try {
484
-
485
- // Then, we do some calls passing this transaction as an option:
486
- const fruit = await Fruit.create({ fruitName: 'Banana', fruitQty: '5', }, { transaction: t });
487
- await fruit.addSibling({ fruitName: 'Litle', fruitQty: '2', }, { transaction: t }); // Error function
488
-
489
- // If the execution reaches this line, no errors were thrown.
490
- // We commit the transaction.
491
- await t.commit();
492
-
493
- } catch (error) {
494
-
495
- // If the execution reaches this line, an error was thrown.
496
- // We rollback the transaction.
497
- await t.rollback();
498
-
499
- }
500
- });
501
- ```
502
-
503
- ## # Generate Helpers ###
504
-
505
- The `helpers` keep the files of functions for process specific something in the project. So, you might create the `helpers` in path `src/helpers` folder.
506
-
507
- ```sh
508
- $ beech make helperName --helper
509
- ```
510
-
511
- ***Example:*** Text editor helper.
512
-
513
- 📂 TextEditor.js
514
- ```js
515
- module.exports = {
516
-
517
- textUpperCase(text) {
518
- return text.toUpperCase();
519
- },
520
-
521
- textTrim(text) {
522
- return text.trim();
523
- },
524
-
525
- ...
526
-
527
- };
528
- ```
529
-
530
- # Authentication (passport-jwt)
531
-
532
- Passport is authentication middleware for Node. It is designed to serve a singular purpose: authenticate requests. When writing modules, encapsulation is a virtue, so Passport delegates all other functionality to the application. This separation of concerns keeps code clean and maintainable, and makes Passport extremely easy to integrate into an application.
533
-
534
- ### Passport-jwt Initialization
535
-
536
- ```sh
537
- $ beech passport init
538
- ```
539
-
540
- After passport initialized the `passport.config.js` it's appeared
541
-
542
- 📂 passport.config.js
543
- ```js
544
- module.exports = {
545
- // Allow for using passport-jwt
546
- jwt_allow: true,
547
-
548
- // custom authenticaiton endpoint name, default `/authentication`
549
- auth_endpoint: "",
550
-
551
- // your jwt secret key
552
- secret: "your_jwt_secret",
553
-
554
- // token expiry time (seconds), default 86400 sec. it's expired in 24 hr.
555
- token_expired: 86400,
556
-
557
- // Allow for using global jwt broken role
558
- jwt_broken_role: [
559
- // { role: [1, 2, 9] },
560
- ],
561
-
562
- model: {
563
- // Main sql connection name. You must make sure connection name like inside `app.config.js` file and choose one connection name.
564
- name: "default_db",
565
-
566
- // table name of users store, default table `users`
567
- table: "",
568
-
569
- // secret user store field for authenticate, default field `username` and `password`
570
- username_field: "",
571
- password_field: "",
572
-
573
- // JWT playload data, You can add it. Example: ["name", "email", ...]
574
- fields: [],
575
-
576
- // Other fields add for authentication.
577
- guard: {
578
- // Basic guard field, Example: ["pin", "hint", "2fa"]
579
- guard_field: [],
580
-
581
- // Advanced guard jwt request (needed some logical from front-end)
582
- advanced_guard: {
583
- allow: false,
584
- entity: "", // default entity `timing`
585
- secret: "top_secret",
586
- time_expired: {
587
- minutes: 1, // should length [0-60]
588
- seconds: 0, // should length [0-60]
589
- },
590
- },
591
- },
592
- },
593
-
594
- // Allow for using request with app_key entity (Every request must be using the app_key entity in headers)
595
- app_key_allow: false
596
-
597
- ...
598
-
599
- };
600
- ```
601
-
602
- **Authentication structure :** Simple ``users`` table:
603
- ```
604
- ==============================================================
605
- | id | username | password | name | email |
606
- --------------------------------------------------------------
607
- | 1 | bombkiml | secret | bombkiml NC. | bomb@bomb.com |
608
- | 2 | johnson | secret | johnson BA. | john@bomb.com |
609
- ```
610
-
611
- When you config passport with ```users``` table already. You will got Auth endpoint in available.
612
- ```js
613
- POST: "/authentication" // Request token
614
- POST: "/authentication/create" // Create new Auth data
615
- PATCH: "/authentication/update/:id" // Update old Auth data (needed id)
616
- ```
617
-
618
- ***XHR Example :***
619
-
620
- ```js
621
- // Request with body for gether Token
622
- POST: "/authentication"
623
- {
624
- username: "bombkiml",
625
- password: "secret"
626
- }
627
-
628
-
629
- // Request with body for Create Auth data
630
- POST: "/authentication/create"
631
- {
632
- username: "add_new_username",
633
- password: "add_new_secret",
634
- name: "add_new_my_name",
635
- email: "add_new_email"
636
- }
637
-
638
-
639
- // Request with body for Update Auth data
640
- PATCH: "/authentication/update/1"
641
- headers: Authorization: Bearer <your_token>
642
- {
643
- username: "update_bombkiml",
644
- password: "update_secret",
645
- name: "update_my_name",
646
- email: "my_update_email@bomb.com"
647
- }
648
- ```
649
-
650
- # Beech Two Factor (2FA)
651
- You can easy using 2 Factor authenticate with ```guard_field``` inside ```passport.config.js``` file and add your Guard field ex: ```2fa``` field for Authenticate Conditions.
652
-
653
- ## # Usage guard (2FA, Other)
654
-
655
- 📂 passport.config.js
656
- ```js
657
- module.exports = {
658
- ...
659
-
660
- guard: {
661
- // Other fields add for authenticate, exmaple ["pin", "hint", "2fa"]
662
- guard_field: ["2fa"], 👈 // your feild guard.
663
-
664
- ...
665
- },
666
-
667
- ...
668
-
669
- }
670
- ```
671
-
672
- ## # Beech Advanced Guard (Timing)
673
- Advance Guard for Protection your Endpoint with Timing. You can allow in object ```advance_guard``` inside ```passport.config.js``` file. So let's go add your Advance Guard Configuration.
674
-
675
- 📂 passport.config.js
676
- ```js
677
- module.exports = {
678
- ...
679
-
680
- guard: {
681
- ...
682
-
683
- // Advanced guard jwt request (needed some logical from front-end)
684
- advanced_guard: {
685
- allow: false, 👈 // advanced guard allow for All Endpoint.
686
- entity: "", // default entity `timing`
687
- secret: "your_advance_guard_secret",
688
- time_expired: {
689
- minutes: 1, // should length [0-60]
690
- seconds: 0, // should length [0-60]
691
- },
692
- },
693
- },
694
-
695
- ...
696
-
697
- }
698
-
699
- ```
700
-
701
- <b>After configure</b>, You must add some logic in your front-end like this.
702
-
703
- Before add logic, We needed [```beech-auth0```](https://github.com/bombkiml/beech-auth0) and [```moment.js```](https://momentjs.com) for apply in Policy.
704
-
705
- ```sh
706
- # NPM
707
- $ npm install --save beech-auth0 moment
708
-
709
- # Yarn
710
- $ yarn add beech-auth0 moment
711
- ```
712
- Now! you can add some logic.
713
- ```js
714
- const { Auth0 } = require("beech-auth0");
715
- const moment = require("moment");
716
-
717
- // Get UNIX TIME with moment
718
- let unix_time = moment().unix();
719
-
720
- // Auth0 Policy.
721
- Auth0(unix_time, 'your_advance_guard_secret', (error, hashing) => {
722
-
723
- // Your XHR request for All Endpoint.
724
- POST: "/authentication"
725
- headers: timing: hashing, 👈 // Assign advance guard entity to headers with callback hashing.
726
-
727
- });
728
-
729
- ```
730
-
731
- ## # Beech User Auth Managements ###
732
- You can easy management `users` data with Beech, Only ```Store, Update``` NO ```Delete```, Anything you can make DELETE endpoint by yourself
733
-
734
- ```js
735
- const { Store, Update } = require("beech-api");
736
- ```
737
-
738
- - ***Store*** users data with ``Store()``
739
- ```js
740
- // prepare data for store users
741
- var data = {
742
- username: "bombkiml",
743
- password: "secret",
744
- name: "bombkiml nc.",
745
- email: "bomb@bomb.com"
746
- }
747
-
748
- Store(data, (err, stored) => {
749
- if (err) throw err;
750
-
751
- // response affected data
752
- console.log(stored.insertId, stored.affectedRows);
753
-
754
- });
755
- ```
756
-
757
- - ***Update*** users data with ``Update()``
758
- ```js
759
- // prepare data for update users
760
- var data = {
761
- password: "new_secret",
762
- name: "bombkiml NC.",
763
- email: "bombkiml@bomb.com"
764
- }
765
-
766
- Update(data, id, (err, updated) => {
767
- if (err) throw err;
768
-
769
- // response affected data
770
- console.log(updated.updateId, updated.affectedRows);
771
-
772
- });
773
- ```
774
-
775
- # Beech with Official Strategy
776
-
777
- Latest supported with ``Google`` and ``Facebook`` Strategy.
778
-
779
-
780
- ## # Google Strategy
781
-
782
-
783
- The Google OAuth 2.0 authentication strategy authenticates users using a Google account and OAuth 2.0 tokens. The strategy requires a verify callback, which accepts these credentials and calls done providing a user, as well as options specifying a client ID, client secret, and callback URL.
784
-
785
- Before your application can make use of Sign In With Google, you must register your app with Google. This can be done in the [APIs & Services](https://console.cloud.google.com/apis) page of the [Google Cloud Platform console.](https://console.cloud.google.com/) Once registered, your app will be issued a client ID and secret which will be used in the strategy configuration.
786
-
787
- Go to open file ``passport.config.js`` and go to ``google strategy`` then turn allow Google Strategy is ``allow: true`` something like this.
788
-
789
- 📂 passport.config.js
790
- ```js
791
- ...
792
-
793
- strategy: {
794
-
795
- google: {
796
-
797
- // Allow for using google strategy
798
- allow: true,
799
-
800
- // Authen profile store fields available: `google_id`, `name`, `email`, `photos`, `locate`
801
- local_profile_fields: {
802
- google_id: "google_id", // Google ID field, default field name: `google_id`
803
- name: "your_name_field",
804
- email: "your_email_field",
805
- photos: "your_profile_url_field",
806
- locate: "" // If you not store set to null or remove it.
807
- },
808
- // Google development Credentials OAuth 2.0 Client IDs
809
- client_id: "GOOGLE_CLIENT_ID",
810
- client_secret: "GOOGLE_CLIENT_SECRET",
811
- // Callback endpoint default `/google/callback`
812
- callbackURL: "",
813
- // Failure redirect to your route
814
- failureRedirect: "/login"
815
- }
816
- }
817
-
818
- ...
819
- ```
820
-
821
- The above code is a configures and registers the Google Strategy.
822
-
823
- - ``allow`` : Turn on/off the Google Strategy config type of ``boolean`` switch by ``true/false``.
824
- - ``google_id`` : Local Google ID field for store Google ID in my local database default field is ``google_id``.
825
- - ``local_profile_fields`` : Local Profile fields for store Google user details.
826
- - ``client_id`` and ``client_secret`` : The options to the Google Strategy constructor must include a ``clientID`` and ``clientSecret``, the values of which are set to the client ID and secret that were obtained when registering your application.
827
- - ``callbackURL`` : When registering your application. A callbackURL must also be included. Google will redirect users to this location after they have authenticated.
828
- - ``failureRedirect`` : When registering your application somthing failure it's redirect to that.
829
-
830
- Place a button on the application's login page, prompting the user to sign in with Google.
831
-
832
- ```html
833
- <a href="/authentication/google" class="button">Sign in with Google</a>
834
- ```
835
-
836
- **Note:** The URL "``/authentication``" will be follow by ``auth_endpoint`` when you custom it.
837
-
838
-
839
- ## # Facebook Strategy
840
-
841
-
842
- Facebook Login allows users to sign in using their Facebook account. Support for Faceboook Login is provided by the ``passport-facebook`` package.
843
-
844
- Before your application can make use of Facebook Login, you must register your app with Facebook. This can be done in the [App dashboard](https://developers.facebook.com/apps) at [Facebook for Developers.](https://developers.facebook.com/) Once registered, your app will be issued an app ID and secret which will be used in the strategy configuration.
845
-
846
- Go to open file ``passport.config.js`` and go to ``facebook strategy`` then turn allow Facebook Strategy is ``allow: true`` something like this.
847
-
848
- 📂 passport.config.js
849
- ```js
850
- ...
851
-
852
- strategy: {
853
-
854
- facebook: {
855
-
856
- // Allow for using facebook strategy
857
- allow: true,
858
-
859
- // Authen profile store fields available: `facebook_id`, `name`, `email`, `photos`, `locate`
860
- local_profile_fields: {
861
- facebook_id: "facebook_id", // Facebook ID field, default field name: `facebook_id`
862
- name: "your_name_field",
863
- email: "your_email_field",
864
- photos: "your_profile_url_field",
865
- locate: "" // If you not store set to null or remove it.
866
- },
867
- // Facebook development Credentials OAuth 2.0
868
- app_id: "FACEBOOK_APP_ID",
869
- app_secret: "FACEBOOK_APP_SECRET",
870
-
871
- // You can allow Permissions facebook profile fields. Learn more (https://developers.facebook.com/docs/graph-api/reference/v13.0/user#readperms)
872
- // **Update 2024, Now! Facebook requests permission for show Email. Learn more (https://developers.facebook.com/docs/permissions)
873
- profileFieldsAllow: [ 'id', 'displayName', 'name', 'photos', 'email', 'location' ], // Default allowed
874
-
875
- // Callback endpoint default `/facebook/callback`
876
- callbackURL: "",
877
- // Failure redirect to your route
878
- failureRedirect: "/login"
879
- }
880
- }
881
-
882
- ...
883
- ```
884
-
885
- The above code is a configures and registers the Facebook Strategy.
886
-
887
- - ``allow`` : Turn on/off the Facebook Strategy config type of ``boolean`` switch by ``true/false``.
888
- - ``facebook_id`` : Local Facebook ID field for store Facebook ID in my local database default field is ``facebook_id``.
889
- - ``local_profile_fields`` : Local Profile fields for store Facebook user details.
890
- - ``app_id`` and ``app_secret`` : The options to the Facebook Strategy must include an app ID and secret. you must register your app with Facebook. This can be done in the [App dashboard](https://developers.facebook.com/apps) at [Facebook for Developers.](https://developers.facebook.com/) Once registered, your app will be issued an ``app ID`` and ``secret`` which will be used in the strategy configuration.
891
- - ``profileFieldsAllow`` : Permissions with Facebook Login. You must allow Permissions facebook profile fields: see more (https://developers.facebook.com/docs/graph-api/reference/v13.0/user#readperms)
892
- - ``callbackURL`` : When registering your application. A callbackURL must also be included. Facebook will redirect users to this location after they have authenticated.
893
- - ``failureRedirect`` : When registering your application somthing failure it's redirect to that.
894
-
895
- Place a button on the application's login page, prompting the user to sign in with Facebook.
896
-
897
- ```html
898
- <a href="/authentication/facebook" class="button">Log In With Facebook</a>
899
- ```
900
-
901
- ❓ **Note:** The URL "``/authentication``" will be follow by ``auth_endpoint`` when you custom it.
902
-
903
- # CORS Origin & Server Configuration
904
- The origin array to the callback can be any value allowed for the origin option of the middleware. Certain CORS requests are considered `complex` and require an initial OPTIONS request (called the `pre-flight request`). You can allowed CORS origin inside file `beech.config.js`
905
-
906
- 📂 beech.config.js
907
- ```js
908
- module.exports = {
909
- defineConfig: {
910
- // Base public path when served in development or production.
911
- base: process.env.NODE_ENV === "production"
912
- ? "/my-api/" // For Production
913
- : "/", // For Development
914
-
915
- server: {
916
- // Client request allow origin whitelist
917
- origin: ["http://example.com", "http://my-webapp:8080", "https://cat.io"],
918
- originSensitive: false, // Sensitive with contrasts wording
919
-
920
- // API Request rate limit (Disabled for Remove it.)
921
- rateLimit: {
922
- windowMs: 15 * 60 * 1000, // 15 minutes
923
- limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
924
- // store: ... , // Redis, Memcached, etc.
925
- // See more: https://www.npmjs.com/package/express-rate-limit#Configuration
926
- },
927
-
928
- // API Duplicate Request (Disabled for Set expiration to 0 zero.)
929
- duplicateRequest: {
930
- expiration: 500, // Can't duplicate request for 5 milliseconds each IP requests per `window`
931
- },
932
- },
933
- },
934
- }
935
- ```
936
-
937
- **Note:** When you must to allowed all Origin. You can assign `*` or `[]` null value to `origin` variable.
938
-
939
- ## # Custom Endpoint Specific Rate Limit
940
- When you need assign specific request Endpoint with [express-rate-limit](https://www.npmjs.com/package/express-rate-limit), You can managemnet with Beech object ```rateLimit``` for your custom Rate Limit like this.
941
-
942
- ```js
943
- const { rateLimit } = require("beech-api").Express;
944
-
945
- // Specific of your rate limit
946
- const specificRateLimit1 = rateLimit({
947
- windowMs: 5 * 60 * 1000, // 5 minutes
948
- limit: 20,
949
- // more...
950
- });
951
-
952
- // Your Endpoints...
953
- endpoint.get("/banana", specificRateLimit1, (req, res) => {
954
- ...
955
- });
956
-
957
- ...
958
- ```
959
-
960
- ## # Custom Endpoint Specific Slow Down
961
- **DON'T DO IT.** &nbsp; Because it's annoying to users.
962
-
963
- When you need assign specific request Endpoint with [express-slow-down](https://www.npmjs.com/package/express-slow-down), You can managemnet with Beech object ```slowDown``` for your custom Slow Down like this.
964
-
965
- ```js
966
- const { slowDown } = require("beech-api").Express;
967
-
968
- // Specific of your slow down
969
- const specificSlowDown1 = slowDown({
970
- windowMs: 15 * 60 * 1000, // 15 minutes
971
- delayAfter: 5, // Allow 5 requests per 15 minutes.
972
- delayMs: (hits) => hits * 100, // Add 100 ms of delay to every request after the 5th one.
973
- // more...
974
-
975
- /**
976
- * So:
977
- *
978
- * - requests 1-5 are not delayed.
979
- * - request 6 is delayed by 600ms
980
- * - request 7 is delayed by 700ms
981
- * - request 8 is delayed by 800ms
982
- *
983
- * and so on. After 15 minutes, the delay is reset to 0.
984
- */
985
- });
986
-
987
- // Your Endpoints...
988
- endpoint.get("/banana", specificSlowDown1, (req, res) => {
989
- ...
990
- });
991
-
992
- ...
993
- ```
994
-
995
- ## # Custom Endpoint Specific Duplicate Request
996
- This middleware to Limit each IP duplicated requests per window.
997
-
998
- When you need assign specific request Endpoint with duplicate request use [express-duplicate-request](https://github.com/bombkiml/express-duplicate-request), You can managemnet with Beech object ```duplicateRequest``` for your custom Duplicate Request like this.
999
-
1000
- ```js
1001
- const { duplicateRequest } = require("beech-api").Express;
1002
-
1003
- // Specific of your duplicate request
1004
- const specificDup1 = duplicateRequest({
1005
- expiration: 500, // Can't duplicate request for 5 milliseconds, Should 0 to disabled
1006
- // more...
1007
- });
1008
-
1009
- // Your Endpoints...
1010
- endpoint.get("/banana", specificDup1, (req, res) => {
1011
- ...
1012
- });
1013
-
1014
- ...
1015
- ```
1016
-
1017
-
1018
-
1019
- # Databases managements
1020
-
1021
- ## # Migrations & Seeder
1022
-
1023
- Just like you use Git / SVN to manage changes in your source code, you can use migrations to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.
1024
-
1025
- You will need [Sequelize CLI.](https://github.com/sequelize/cli) The CLI ships support for [migrations](https://sequelize.org/v5/manual/migrations.html) and project.
1026
-
1027
- ## # Usage
1028
-
1029
- To create an empty project you will need to execute `init` command
1030
-
1031
- ```sh
1032
- $ npx sequelize-cli init
1033
- ```
1034
-
1035
- This will create following folders inside `databases` folder.
1036
-
1037
- - `config`, contains config file, which tells CLI how to connect with database.
1038
- - `models`, contains all models for your project.
1039
- - `migrations`, contains all migration files.
1040
- - `seeders`, contains all seed files.
1041
-
1042
- ## # Configuration
1043
-
1044
- Before continuing further we will need to tell CLI how to connect to database. To do that let's open default config file `databases/config/database.json` It looks something like this:
1045
-
1046
- ```json
1047
- {
1048
- "development": {
1049
- "username": "root",
1050
- "password": null,
1051
- "database": "database_development",
1052
- "host": "127.0.0.1",
1053
- "dialect": "mysql"
1054
- },
1055
- "test": {
1056
- "username": "root",
1057
- "password": null,
1058
- "database": "database_test",
1059
- "host": "127.0.0.1",
1060
- "dialect": "mysql"
1061
- },
1062
- "production": {
1063
- "username": "root",
1064
- "password": null,
1065
- "database": "database_production",
1066
- "host": "127.0.0.1",
1067
- "dialect": "mysql"
1068
- }
1069
- }
1070
- ```
1071
-
1072
- ❓ **Note:** The database connect default port 3306 if you another port you can add object ``port`` in config.
1073
-
1074
- ❓ **Note:** If your database doesn't exists yet, you can just call `npx sequelize-cli db:create` command. With proper access it will create that database for you.
1075
-
1076
- ## # Creating first Migrations
1077
-
1078
- Create `model` use `model:generate` command. This command requires two options.
1079
-
1080
- - `--name`, Name of the model
1081
- - `--attributes`, List of model attributes
1082
-
1083
- Let's create a model name example `User`. See more about of [Datatypes](https://sequelize.org/v5/manual/data-types.html)
1084
-
1085
- ```sh
1086
- $ npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string,birhday:date
1087
- ```
1088
-
1089
- ## # Migrations Up and Down
1090
-
1091
- Until this step, we haven't inserted anything into the database. We have just created required model and migration files for our first model User.
1092
-
1093
- - **Migrate Up** : you can create that table in database you need to run db:migrate command.
1094
-
1095
- ```sh
1096
- $ npx sequelize-cli db:migrate
1097
- ```
1098
-
1099
- - **Migrate Down** : you can use `db:migrate:undo`, this command will revert most recent migration.
1100
- ```sh
1101
- $ npx sequelize-cli db:migrate:undo
1102
- ```
1103
-
1104
- ## # Creating First Seeder
1105
-
1106
- To manage all data migrations you can use seeders. Seed files are some change in data that can be used to populate database table with sample data or test data.
1107
-
1108
- Let's create a seed file which will add a demo user to our User table.
1109
-
1110
- ```sh
1111
- $ npx sequelize-cli seed:generate --name user
1112
- ```
1113
-
1114
- ## # Seeder Up and Down
1115
-
1116
- In last step you have create a seed file. It's still not committed to database. To do that we need to run a simple command.
1117
-
1118
- - **Seed Up** : you can execute that seed file and you will have a user inserted into `User` table.
1119
-
1120
- ```sh
1121
- $ npx sequelize-cli db:seed:all
1122
- ```
1123
-
1124
- - **Seed Down** : seeders can be undone if they are using any storage. There are two commands available for that:
1125
-
1126
- If you wish to undo most recent seed
1127
-
1128
- ```sh
1129
- $ npx sequelize-cli db:seed:undo
1130
- ```
1131
-
1132
- If you wish to undo a specific seed
1133
-
1134
- ```
1135
- $ npx sequelize-cli db:seed:undo --seed <seederName>
1136
- ```
1137
-
1138
- If you wish to undo all seeds
1139
-
1140
- ```sh
1141
- $ npx sequelize-cli db:seed:undo:all
1142
- ```
1143
-
1144
- # Testing
1145
-
1146
- Test using [Jest](https://jestjs.io/en/) for testing the project. Jest is a delightful JavaScript Testing Framework with a focus on simplicity. Learn more [Jest docs](https://jestjs.io/docs/en/getting-started.html)
1147
-
1148
- So, When you make the new endpoints it's automatic create test file end with `.spec.js` in `__test__` folder with constant `baseUrl` variable and `axios` package.
1149
-
1150
- Example endpoints testing :
1151
-
1152
- 📂 fruit-endpoints.spec.js
1153
- ```js
1154
- const endpoint = baseUrl.concat("/fruit");
1155
-
1156
- describe("Test endpoint : " + endpoint, () => {
1157
- it("Truthy!", () => {
1158
- expect("/fruit").toBeTruthy();
1159
- });
1160
-
1161
- it("Respond with basic GET status code 200", (done) => {
1162
- axios.get(endpoint).then((res) => {
1163
- expect(200).toEqual(res.data.code);
1164
- done();
1165
- });
1166
- });
1167
- });
1168
- ```
1169
-
1170
-
1171
- # Implementation
1172
-
1173
- ## # Implement with [Docker](https://www.docker.com)
1174
-
1175
- [Docker](https://www.docker.com) is an open platform for developing, shipping, and running applications. Docker enables you to separate your applications from your infrastructure so you can deliver software quickly.
1176
-
1177
- - ### **Create Dockerfile**
1178
-
1179
- Docker builds images automatically by reading the instructions from a Dockerfile -- a text file that contains all commands, in order, needed to build a given image. A Dockerfile adheres to a specific format and set of instructions which you can find at [Dockerfile reference](https://docs.docker.com/engine/reference/builder/).
1180
-
1181
- 📂 Dockerfile
1182
- ```js
1183
- FROM node:14.19-alpine
1184
- ENV NODE_ENV=production
1185
- WORKDIR /usr/src/api
1186
- COPY ["package.json", "package-lock.json*", "./"]
1187
- RUN npm install --production --silent && mv node_modules .
1188
- COPY . .
1189
- EXPOSE 9000
1190
- CMD ["node", "./node_modules/beech-api/packages/cli/beech"]
1191
- ```
1192
-
1193
- - ### **Docker build image**
1194
-
1195
- The docker build command builds an image from a Dockerfile and a context. The build’s context is the set of files at a specified location ```PATH``` or ```URL```. The PATH is a directory on your local filesystem. The URL is a Git repository location.
1196
-
1197
- ```sh
1198
- $ docker build -t <imageName> .
1199
- ```
1200
-
1201
- **Note:** You can specify a repository and tag at which to save the new image : ``` $ docker build -t <imageName>:<tags> . ```
1202
-
1203
- - ### **Run docker**
1204
-
1205
- After create ``image`` you can run docker engine following :
1206
-
1207
- - ### **Docker Container (Standalone)**
1208
- ```sh
1209
- $ docker run -d -p 9000:9000 --name <containerName> <imageName>
1210
- ```
1211
-
1212
- - ### **Create Docker Swarm (Cluster)**
1213
- ```sh
1214
- # Initiate swarm
1215
- $ docker swarm init
1216
-
1217
- # Run docker service
1218
- $ docker service create --replicas <instances> --name <containerName> --publish 9000:9000 <imageName>
1219
- ```
1220
-
1221
- ## # Implement with [PM2](https://pm2.keymetrics.io/)
1222
- [PM2](https://pm2.keymetrics.io/) is a daemon process manager that will help you manage and keep your application online. Getting started with PM2 is straightforward, it is offered as a simple and intuitive CLI, installable via [NPM](https://www.npmjs.com/).
1223
-
1224
- ```sh
1225
- # Start service as standalone
1226
- $ pm2 start ./node_modules/beech-api/packages/cli/beech --name <serviceName>
1227
-
1228
- # OR
1229
-
1230
- # Start service as cluster mode
1231
- $ pm2 start ./node_modules/beech-api/packages/cli/beech --name <serviceName> -i <instances>
1232
- ```
1233
-
1234
- # Development
1235
-
1236
- Want to contribute or join for great job!, You can contact to me via
1237
-
1238
- - GitHub: [bombkiml/beech-api - issues](https://github.com/bombkiml/beech-api/issues)
1239
- - E-mail: nattapat.jquery@gmail.com
1240
- - Facebook: [https://www.facebook.com/bombkiml](https://www.facebook.com/bombkiml)
1241
-
1242
- # License
1243
-
1244
- The Beech API framework is open-sourced software licensed under the [MIT license.](https://opensource.org/licenses/MIT)
1
+ [![N|Solid](https://i.ibb.co/NKxx9NQ/beech320.jpg)](https://github.com/bombkiml)
2
+
3
+ # Beech API framework
4
+ #### Auto endpoint v.3.9.0 (LTS)
5
+
6
+ [![beech-api release](https://img.shields.io/github/v/release/bombkiml/beech-api)](https://github.com/bombkiml/beech-api/releases/)
7
+ [![PyPI license](https://shields.io/pypi/l/ansicolortags.svg)](https://github.com/bombkiml/beech-api/blob/master/README.md)
8
+
9
+ # What is Beech API ?
10
+
11
+ The Beech API is API framework, It's help you with very easy to create API project under [Node.js](https://nodejs.org)
12
+
13
+ ## Let's go
14
+ - <b>[Installation](#installation)</b>
15
+ - <b>[Creating a project](#creating-a-project)</b>
16
+ - <b>[Upgrade to latest version](#upgrade-to-latest-version)</b>
17
+ - <b>[Beech CLI tool available](#beech-cli-tool-available)</b>
18
+ - ✨ <b>Automation Endpoints with CRUD</b>
19
+ - [Database Connection](#database-connection)
20
+ - [Model](#models)
21
+ - [Retrieving data with Query String](#retrieving-data-with-query-string)
22
+ - Conditions
23
+ - Grouping
24
+ - Ordering
25
+ - Timestamps (Add-on in Store and Update)
26
+ - [Transactions](#-transactions)
27
+ - [Disorganized transactions](#way-1---disorganized-transactions-)
28
+ - [Organized transactions](#way-2---organized-transactions-)
29
+ - [Transactions set Isolation levels](#way-3---transactions-set-isolation-levels-)
30
+ - [Endpoints](#endpoints)
31
+ - [Helpers](#helpers)
32
+ - 🔐 <b>System Management of Authentication</b>
33
+ - [Authentication Manegement](#authentication-passport-jwt)
34
+ - [Request Token](#request-token)
35
+ - [Beech Guard](#beech-guard)
36
+ - Verify Identity Management
37
+ - Two Factor (2fa, OTP, etc.)
38
+ - [Beech User Authentication Managements](#-beech-user-authentication-managements)
39
+ - Create Auth
40
+ - Update Auth
41
+ - 🛠️ <b>Safe Endpoints Request</b>
42
+ - [Rate Limit](#-custom-endpoint-specific-rate-limit)
43
+ - [Slow Down](#-custom-endpoint-specific-slow-down)
44
+ - [Block Duplicate Request per Window](#-custom-endpoint-specific-duplicate-request)
45
+ - [JWT Broken Role](#jwt-broken-role)
46
+ - [Advance Guard (Timimg)](#-beech-advanced-guard-timing)
47
+ - 🙂 <b>Hight Security under passport-jwt, oauth2</b>
48
+ - 🌐 <b>Supported Official Strategy</b>
49
+ - [Google](#-google-strategy)
50
+ - [Facebook](#-facebook-strategy)
51
+ - 🖥️ <b>CORS Origin & Server Configuration</b>
52
+ - [Config Base public path `./`](#cors-origin--server-configuration)
53
+ - [Allow origin whitelist](#cors-origin--server-configuration)
54
+ - 📚 <b>Databases Managements</b>
55
+ - [Migrations](#databases-managements)
56
+ - [Seeder](#-creating-first-seeder)
57
+ - <b>Testing</b>
58
+ - [Jest](#testing)
59
+ - 🏃 <b>Implementration</b>
60
+ - [Building for Production](#building-for-production)
61
+ - [Docker](#implementation)
62
+ - [PM2](#-implement-with-pm2)
63
+
64
+ # Environment
65
+
66
+ - [`Node.js`](https://nodejs.org) >= 18.18.0+ (recommended)
67
+
68
+ # Installation
69
+
70
+ Beech API needed Node.js version 18.18.0 or above. You can management multiple versions on the same machine with [nvm](https://github.com/creationix/nvm) or [nvm-windows](https://github.com/coreybutler/nvm-windows).
71
+
72
+ <b>So, Let's go to install</b> `beech-api`
73
+
74
+ ```sh
75
+ # NPM
76
+ $ npm install beech-api --global
77
+
78
+ # Yarn
79
+ $ yarn global add beech-api
80
+ ```
81
+
82
+ Installation demo:
83
+
84
+ [Demo 1](https://i.ibb.co/TBjNgVrF/1-11.gif)
85
+ ![Alt Text](https://i.ibb.co/TBjNgVrF/1-11.gif)
86
+
87
+ [Demo 2](https://i.ibb.co/wrdgyzDP/ezgif-8539024298ec62a9.gif)
88
+ ![Alt Text](https://i.ibb.co/wrdgyzDP/ezgif-8539024298ec62a9.gif)
89
+
90
+ After installation, you will have access to the `beech-app` binary in your command line.
91
+ You can check you have the right version with this command:
92
+
93
+ ```sh
94
+ $ beech-app --version
95
+ ```
96
+
97
+ # Creating a project
98
+
99
+ Create a new project run:
100
+
101
+ ```sh
102
+ $ beech-app create hello-world
103
+ ```
104
+ Run your project:
105
+ ```sh
106
+ $ cd hello-world
107
+
108
+ $ npm run dev
109
+ # OR
110
+ $ yarn dev
111
+ ```
112
+
113
+ ❓ **Note:** The Beech API it's start server at [http://localhost:9000](http://localhost:9000) you can change new a port in `app.config.js` file.
114
+
115
+
116
+ # Upgrade to latest version
117
+ The Beech API upgrade to latest version command avariable :
118
+
119
+ ```sh
120
+ // Project upgrade
121
+ $ beech-app update
122
+
123
+ // Global upgrade
124
+ $ beech-app update -g, --global
125
+ ```
126
+
127
+ # Beech CLI tool available
128
+ After installation, you will have access to the `beech` binary in your command line.
129
+ The `beech` command has a number of options and you can explore them all by running:
130
+
131
+ ```sh
132
+ $ beech --help
133
+ ```
134
+
135
+ The `beech` command line available:
136
+
137
+ ```
138
+ Usage:
139
+ $ beech [options] [arguments] [special]
140
+
141
+ Options:
142
+ ?, -h, --help Display this help message.
143
+ -v, --version Display the application version.
144
+
145
+ The following commands are available:
146
+
147
+ $ beech make <endpoint> Create a new Endpoints and unit test file,
148
+ You might using [special] `-R, --require`
149
+ for choose Model(s) used to endpoint file.
150
+
151
+ $ beech make <model> -M, --model Create a new Models file, You might using
152
+ [special] `--no-comment` for ignore comment
153
+ Table Property in your Schema.
154
+
155
+ $ beech update model <model_name> Update new Table Structure for latest, You
156
+ might using [special] `--no-comment` for
157
+ ignore comment Table Property in your Schema.
158
+
159
+ $ beech make <helper> --helper Create a new Helpers file.
160
+ $ beech passport init Initialize authentication with passport-jwt.
161
+ $ beech skd init Initialize Job Scheduler file.
162
+ $ beech key:generate, key:gen Re-Generate application key (Dangerous!).
163
+ $ beech hash:<text> Hash text for Access to Database connection.
164
+ ```
165
+ ❓ **Note:** Every to create new project will be generated new ``app_key`` in ``app.config.js`` file.
166
+
167
+ ❓ **Note:** If you can re-generate. Can use command ``$ beech key:generate`` or ``$ beech key:gen``
168
+
169
+ # Database connection
170
+
171
+ You might connection to Database with `database_config` object in `app.config.js` file. Anything can support to multiple Database connections.
172
+
173
+ The connection base on `pool_base` in `global.config.js` file.
174
+
175
+ - `basic` = Support only Raw Query with Only MySQL.
176
+ - `sequelize` = Support PDO, Raw Query with various Database Engine.
177
+
178
+ In case Access to Database must to Hash the `username` and `password` with Beech CLI like this.
179
+
180
+ ```sh
181
+ // Hash database username
182
+ $ beech hash:root
183
+ Output: m42BVxQ6Q4kLdRX7xS_Hm7WbQiNqShJDvw9SLCgI431oafWBtQJoJDnoCL
184
+
185
+ // Hash database password
186
+ $ beech hash:password
187
+ Output: FjgcgJPylkV7EeQJjea_EeifPwaHVO9onD3ATk3YYAyvjtMGu3dcDS0ejA
188
+
189
+ ```
190
+ ***For Example :***
191
+
192
+ 📂 app.config.js
193
+ ```js
194
+ // Database configuration Only Basic & Sequelize (needed Hash)
195
+
196
+ ...
197
+
198
+ database_config: [
199
+ {
200
+ dialect: "mysql",
201
+ name: "mysql_my_store_db",
202
+ host: "localhost",
203
+ username: "m42BVxQ6Q4kLdRX7xS_Hm7WbQiNqShJDvw9SLCgI431oafWBtQJoJDnoCL",
204
+ password: "FjgcgJPylkV7EeQJjea_EeifPwaHVO9onD3ATk3YYAyvjtMGu3dcDS0ejA",
205
+ database: "my_store_db",
206
+ port: "3306",
207
+
208
+ // Specify global options, which are used when Define is called.
209
+ define: {
210
+ charset: "utf8",
211
+ freezeTableName: true,
212
+ ...
213
+ },
214
+
215
+ timezone: "+07:00", // Example: GMT+2
216
+ // or use a named timezone supported by Intl.Locale
217
+ // timezone: 'America/Los_Angeles',
218
+
219
+ logging: console.log, // SQL trace logs. Learn more: https://sequelize.org/docs/v6/getting-started/#logging
220
+
221
+ is_connect: true, // Boolean, Turn ON/OFF to connect
222
+ },
223
+
224
+ ...
225
+
226
+ ],
227
+
228
+ ...
229
+ ```
230
+ ❓ **Caution! :** Every re-new generate `app_key`. Must to new Hash your Access and change to ALL Database connections.
231
+
232
+ ❓ **Development** : You can add ```dev: true``` in ```main_config``` for a better experience.
233
+
234
+ # Models
235
+
236
+ The `models` keep the files of function(s) data managemnets for Retriving, Creating, Updating and Destroying (CRUD). for understanding you might make model name same your table name inside `src/models` folder.
237
+
238
+ ```sh
239
+ $ beech make modelName --model
240
+ ```
241
+
242
+ ## # Model (Basic)
243
+
244
+ Basic model only support `MySQL` Raw Query format and freedom of your SQL query
245
+
246
+ **Note:** The Basic pool engine it's not support auto Endpoints.
247
+
248
+
249
+ ***For example :***
250
+
251
+ 📂 models/Fruit.js
252
+ ```js
253
+ module.exports = {
254
+
255
+ // Example basic function get data
256
+ getData() {
257
+
258
+ return {
259
+ id: 1,
260
+ name: "John Doe",
261
+ }
262
+
263
+ },
264
+
265
+ // Example basic function get data from MySQL table
266
+ getFruit() {
267
+
268
+ // calling Pool connection name by `mysql.default_db`
269
+ mysql.default_db.query("SELECT * FROM fruit", (err, results) => {
270
+
271
+ if (err) { throw err }
272
+ return results;
273
+
274
+ });
275
+
276
+ }
277
+
278
+ };
279
+ ```
280
+
281
+ ## # Model (Sequelize)
282
+
283
+ Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, Microsoft SQL Server, Oracle Database, Amazon Redshift and Snowflake’s Data Cloud. It features solid transaction support, relations, eager and lazy loading, read replication and more. <br/>You can learn more: [Sequelize docs](https://sequelize.org/docs/v6)
284
+
285
+ You can asign more DataTypes, Learn more : [Sequelize docs](https://sequelize.org/docs/v6/core-concepts/model-basics/#data-types)
286
+
287
+ **Note:** When you generate a model it's create table structure for automatically for you.
288
+
289
+ ***For example :***
290
+
291
+ 📂 models/Fruit.js
292
+ ```js
293
+ const { Schema } = require("beech-api");
294
+
295
+ // Define table Schema with `Schema(sql.default_db)` connection name
296
+ const Fruit = Schema(sql.default_db).define("fruit", {
297
+ fruit_id: {
298
+ field: "id", // Rename PK field to fruit_id Ref: `id` field in fruit table
299
+ type: DataTypes.INTEGER,
300
+ autoIncrement: true,
301
+ primaryKey: true
302
+ },
303
+ friut_uuid: {
304
+ field: "uuid",
305
+ type: DataTypes.STRING(100),
306
+ allowNull: true,
307
+ defaultValue: DataTypes.UUIDV4,
308
+ },
309
+ fruitName: DataTypes.STRING,
310
+ fruitQty: DataTypes.INTEGER,
311
+ fruitPrice: {
312
+ type: DataTypes.INTEGER,
313
+ allowNull: false, // Allow null feilds
314
+ },
315
+ sort: DataTypes.STRING,
316
+ createdAt: {
317
+ type: DataTypes.DATE,
318
+ allowNull: false,
319
+ defaultValue: DataTypes.NOW,
320
+ },
321
+ updatedAt: {
322
+ type: DataTypes.DATE,
323
+ allowNull: true,
324
+ },
325
+ }, {
326
+ // Enables timestamps with createdAt and updatedAt
327
+ timestamps: true,
328
+ // Custom field names createdAt and updatedAt
329
+ createdAt: "createdAt",
330
+ updatedAt: "updatedAt",
331
+ });
332
+
333
+ Fruit.options = {
334
+ // Choose one for Allow magic generate default Endpoint (CRUD), It's like magic creating The endpoints for you (CRUD) ✨
335
+
336
+ // Option 1: Allow all methods
337
+ defaultEndpoint: true,
338
+
339
+ // Option 2: Allow with specific per methods
340
+ defaultEndpoint: {
341
+ GET: true,
342
+ POST: {
343
+ allow: true, // allow Auto-Endpoint
344
+ jwt: {
345
+ allow: true, // allow JWT
346
+ broken_role: [
347
+ { role: [1, 2] },
348
+ ],
349
+ },
350
+ // Rate Limit for POST
351
+ rate_limit: {
352
+ windowMs: 15 * 60 * 1000, // 15 minutes
353
+ limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
354
+ // store: ... , // Redis, Memcached, etc.
355
+ // See more: https://www.npmjs.com/package/express-rate-limit#Configuration
356
+ },
357
+ // Duplicate Request for POST
358
+ duplicate_request: {
359
+ expiration: 500, // Can't duplicate request for 5 milliseconds each IP requests per `window` (Disabled for Set expiration to 0 zero.)
360
+ },
361
+ },
362
+ PATCH: false,
363
+ DELETE: false,
364
+ },
365
+
366
+ limitRows: 100, // Limit rows default 100
367
+ };
368
+
369
+ // Example Finder by id (ORM), Learn more: https://sequelize.org/docs/v6/core-concepts/model-querying-finders/
370
+ function exampleFindOneFruitById(id) {
371
+ return Fruit.findOne({ where: { id: id } });
372
+ }
373
+
374
+ // Example Raw Query with Model Instances. This allows you to easily map a query to a predefined model
375
+ function exampleGetAllFruitWithModelInstance(id) {
376
+ return Fruit.query("SELECT * FROM fruit", {
377
+ model: Fruit, // When JOIN table needed register that table [Fruit, ...]
378
+ mapToModel: true // pass true here if you have any mapped fields
379
+ });
380
+ }
381
+
382
+ // Example Raw Query, Learn more: https://sequelize.org/docs/v6/core-concepts/raw-queries/
383
+ function exampleGetAllFruit(id) {
384
+ return Fruit.query("SELECT * FROM fruit");
385
+ }
386
+
387
+ ...
388
+
389
+ // Export Schema, Function, ...
390
+ module.exports = {
391
+ Fruit,
392
+ exampleFindOneFruitById,
393
+ exampleGetAllFruitWithModelInstance,
394
+ exampleGetAllFruit,
395
+ ...
396
+ };
397
+ ```
398
+
399
+ ## Retrieving data with Query String
400
+
401
+ Now you can add Query String with Conditional, Grouping and Ordering (Now Support Readonly for GET method)
402
+
403
+ ### That's cool! It's like magic Creating The Endpoints for you (CRUD) ✨
404
+
405
+ <b style="font-size:12pt">For Example, Now!</b>, You can request to `/fruit` with methods GET, POST, PATCH and DELETE like this.
406
+
407
+ | Efficacy | Method | Endpoint | Body | Mode |
408
+ |:---------|:---------|:-----------------------|:-------------|:--------|
409
+ | Create | POST | /fruit | { } | Single |
410
+ | Create | POST | /fruit | [ ] | Bulk |
411
+ | Read | GET | /fruit | No | Fetch |
412
+ | Read | GET | /fruit/:limit/:offset | No | Fetch |
413
+ | Read | GET | /fruit?someField=1 | No | Fetch |
414
+ | Read | GET | /fruit?orderby=sort | No | Fetch |
415
+ | Read | GET | /fruit?groupby=id | No | Fetch |
416
+ | Update | PATCH | /fruit/:id | { } | Single |
417
+ | Delete | DELETE | /fruit/:id | No | Single |
418
+
419
+ Add some Basic Conditions, Grouping and Ordering with `QUERY STRING` under GET methods<br/>
420
+
421
+ Retrieving `fruit` data with GET : `/fruit?someField=[eq,1]&groupby=[id]&orderby=[id,desc]`
422
+
423
+ ***For Example :***
424
+
425
+ ```java
426
+ // WHERE Conditions
427
+ GET: /fruit?id=1 // id = 1
428
+ GET: /fruit?isActived=[eq,1] // isActived = 1
429
+ GET: /fruit?fruitName=[like,Banana%] // fruitName LIKE 'Banana%' (Not allow with date, time)
430
+ GET: /fruit?cost=[gt,50]&qty=[lt,10] // cost > 50 AND qty < 10
431
+ GET: /fruit/10/0?qty=[lt,10] // qty < 10 LIMIT 0,10
432
+
433
+ // Grouping
434
+ GET: /fruit?groupby=id // GROUP BY id
435
+ GET: /fruit?groupby=[id,fruitName] // GROUP BY id, fruitName
436
+
437
+ // Ordering
438
+ GET: /fruit?oderby=id // ORDER BY id ASC
439
+ GET: /fruit?oderby=[sort,desc] // ORDER BY sort DESC
440
+ ```
441
+
442
+ For usage avariable:
443
+
444
+ ```java
445
+ // Basics conditions
446
+ =3 // = 3
447
+ =[eq,3] // = 3
448
+ =[ne,20] // != 20
449
+ =[is,null] // IS NULL
450
+ =[not,null] // IS NOT NULL
451
+ =[or,[5,6]] // (someField = 5) OR (someField = 6) // Not support NULL value
452
+
453
+ // Number comparisons conditions
454
+ =[gt,6] // > 6
455
+ =[gte,6] // >= 6
456
+ =[lt,10] // < 10
457
+ =[lte,10] // <= 10
458
+ =[between,[6,10]] // BETWEEN 6 AND 10
459
+ =[between,["2025-01-01","2025-04-30"]] // BETWEEN "2025-01-01" AND "2025-04-30"
460
+ // When assign Datetime format will only support field datatype is `Date`, `Datetime`, `Time`
461
+
462
+ // OR You can assign Datetime like this.
463
+ =[between,["2025-01-01 12:00:00","2025-04-30 15:00:00"]] // BETWEEN "2025-01-01 12:00:00" AND "2025-04-30 15:00:00"
464
+
465
+ =[notBetween,[11,15]] // NOT BETWEEN 11 AND 15
466
+
467
+ // Other operators conditions
468
+ =[in,[1,2,3]], // IN [1, 2, 3]
469
+ =[notIn,[1,2,3]], // NOT IN [1, 2, 3]
470
+ =[like,"%Banana"] // LIKE '%Banana' (Freestyle LIKE)
471
+
472
+ =[notLike,"Banana"] // NOT LIKE 'Banana'
473
+ =[startsWith,"Banana"] // LIKE 'Banana%'
474
+ =[endsWith,"Banana"] // LIKE '%Banana'
475
+ =[substring,"Banana"] // LIKE '%Banana%'
476
+
477
+ // Grouping
478
+ groupby=id // GROUP BY id
479
+ groupby=[id] // ORDER BY id
480
+ groupby=[id,fruitName] // ORDER BY id, fruitName
481
+
482
+ // Ordering
483
+ oderby=id // ORDER BY id ASC (Basic usage default Ascending)
484
+ oderby=[id,asc] // ORDER BY id ASC
485
+ oderby=[id,desc] // ORDER BY id ASC
486
+ oderby=[[id,desc],[sort,asc]] // ORDER BY id DESC, sort ASC
487
+ ```
488
+
489
+ ## # Transactions
490
+
491
+ Sequelize does not use transactions by default. However, for production-ready usage of Sequelize, you should definitely configure Sequelize to use transactions.
492
+
493
+ Beech use Sequelize supports three ways of using transactions:
494
+
495
+ - ### Way 1 - Disorganized transactions :
496
+ ```js
497
+ // First, we start a transaction from your connection and save it into a variable
498
+ const t = await Fruit.transaction();
499
+
500
+ try {
501
+
502
+ // Then, we do some calls passing this transaction as an option:
503
+ const fruit = await Fruit.create({ fruitName: 'Banana', fruitQty: '5', }, { transaction: t });
504
+ await fruit.addSibling({ fruitName: 'Litle', fruitQty: '2', }, { transaction: t }); // Error function
505
+
506
+ // If the execution reaches this line, no errors were thrown.
507
+ // We commit the transaction.
508
+ await t.commit();
509
+
510
+ } catch (error) {
511
+
512
+ // If the execution reaches this line, an error was thrown.
513
+ // We rollback the transaction.
514
+ await t.rollback();
515
+
516
+ }
517
+ ```
518
+
519
+ - ### Way 2 - Organized transactions :
520
+ ```js
521
+ // First, we start a transaction from your connection and save it into a variable
522
+ Fruit.transaction(async t => {
523
+ try {
524
+
525
+ // Then, we do some calls passing this transaction as an option:
526
+ const fruit = await Fruit.create({ fruitName: 'Banana', fruitQty: '5', }, { transaction: t });
527
+ await fruit.addSibling({ fruitName: 'Litle', fruitQty: '2', }, { transaction: t }); // Error function
528
+
529
+ // If the execution reaches this line, no errors were thrown.
530
+ // We commit the transaction.
531
+ await t.commit();
532
+
533
+ } catch (error) {
534
+
535
+ // If the execution reaches this line, an error was thrown.
536
+ // We rollback the transaction.
537
+ await t.rollback();
538
+
539
+ }
540
+ });
541
+ ```
542
+
543
+ - ### Way 3 - Transactions set Isolation levels :
544
+
545
+ The possible [isolations levels](https://sequelize.org/docs/v6/other-topics/transactions/#isolation-levels) to use when starting a transaction:
546
+
547
+ ```js
548
+ const { Transaction } = require('sequelize');
549
+
550
+ // First, we start a transaction from your connection and save it into a variable
551
+ Fruit.transaction(
552
+ {
553
+ isolationLevel: Transaction.ISOLATION_LEVELS.SERIALIZABLE,
554
+ },
555
+ async t => {
556
+ try {
557
+
558
+ // Then, we do some calls passing this transaction as an option:
559
+ const fruit = await Fruit.create({ fruitName: 'Banana', fruitQty: '5', }, { transaction: t });
560
+ await fruit.addSibling({ fruitName: 'Litle', fruitQty: '2', }, { transaction: t }); // Error function
561
+
562
+ // If the execution reaches this line, no errors were thrown.
563
+ // We commit the transaction.
564
+ await t.commit();
565
+
566
+ } catch (error) {
567
+
568
+ // If the execution reaches this line, an error was thrown.
569
+ // We rollback the transaction.
570
+ await t.rollback();
571
+
572
+ }
573
+ });
574
+ ```
575
+
576
+ # Endpoints
577
+
578
+ The `endpoints` keep the endpoints basic request files currently support `GET`, `POST`, `PUT`, `PATCH` and `DELETE`.
579
+
580
+ So, you might create new endpoints with constant `endpoint` object variable in `src/endpoints/` folder and file neme must be end with `-endpoints.js`
581
+
582
+ ```sh
583
+ $ beech make endpointName
584
+ ```
585
+ You might using [special] `-R, --require` for choose Model(s) used for that endpoint.
586
+
587
+ **Note:** If you generate Endpoint Name same Auto-Endpoint it's Override to main Auto-Endpoint to you, (You always have priority).
588
+
589
+ ***For Example :***
590
+
591
+ 📂 endpoints/fruit-endpoints.js
592
+ ```js
593
+ // Require Model schema, Function & Others
594
+ const { Fruit } = require("@/models/Fruit");
595
+
596
+ exports.init = () => {
597
+
598
+ // GET method
599
+ endpoint.get("/fruit", Credentials, async (req, res) => {
600
+ // example call Fruit model for get data
601
+ res.json({
602
+ code: 200,
603
+ status: "SUCCESS",
604
+ results: await Fruit.findAll();
605
+ });
606
+ });
607
+
608
+
609
+ // POST method
610
+ endpoint.post("/fruit", Credentials, (req, res) => {
611
+ // @response
612
+ res.json({
613
+ code: 200,
614
+ status: "SUCCESS",
615
+ message: "POST request at /fruit",
616
+ result: {
617
+ id: req.body.id,
618
+ name: req.body.name,
619
+ },
620
+ });
621
+ });
622
+
623
+
624
+ // PUT method
625
+ endpoint.put("/fruit/:id", Credentials, (req, res) => {
626
+ // @response
627
+ res.json({
628
+ code: 200,
629
+ status: "SUCCESS",
630
+ message: "PUT request at /fruit/" + req.params.id,
631
+ });
632
+ });
633
+
634
+
635
+ // DELETE method
636
+ endpoint.delete("/fruit/:id", Credentials, (req, res) => {
637
+ // @response
638
+ res.json({
639
+ code: 200,
640
+ status: "SUCCESS",
641
+ message: "DELETE request at /fruit/" + req.params.id,
642
+ });
643
+ });
644
+
645
+ ...
646
+
647
+ }
648
+ ```
649
+
650
+ # JWT Broken Role
651
+
652
+ The **JWT Broken Role** mechanism provides a flexible way to bypass or override role-based authorization rules when using JWT.
653
+
654
+ #### It can be applied in three different levels, depending on your use case.
655
+
656
+ | Priority | Level | Scope | Best For |
657
+ |:---------|:--------------------------------|:-------------------------|:--------------------------------|
658
+ | 3rd | Global (``passport.config.js``) | All endpoints | Common authorization exceptions |
659
+ | 2nd | Model-level options | Per model & HTTP method | Structured, reusable rules |
660
+ | 1st | Endpoint middleware | Single endpoint | Custom or special cases |
661
+
662
+ This multi-layer approach allows you to design **secure, flexible, and maintainable JWT authorization flows**.
663
+
664
+ ### 1. Global Configuration (passport.config.js) - Priority 3
665
+
666
+ You can define global JWT Broken Role rules that apply to all endpoints by configuring them in ``passport.config.js``.
667
+ ```js
668
+ module.exports = {
669
+ // Enable JWT authentication
670
+ jwt_allow: true,
671
+
672
+ ...
673
+
674
+ // Global JWT broken role configuration
675
+ jwt_broken_role: [
676
+ {
677
+ role: [0, 2, 4],
678
+ email: "john.doe@company.com",
679
+ }, // Basic role matching
680
+
681
+ {
682
+ role: { $in: [0, 2, 4] },
683
+ email: { $regex: /@company\.com$/ },
684
+ }, // Advanced matching using operators
685
+ ],
686
+
687
+ ...
688
+ };
689
+ ```
690
+
691
+ **Use cases**
692
+
693
+ - Apply common authorization exceptions across the entire application
694
+ - Support both simple role arrays and advanced operators (``$in``, ``$regex``, etc.)
695
+
696
+ ### 2. Model-Level Configuration (Per HTTP Method) - Priority 2
697
+
698
+ You can configure JWT and Broken Role rules per model and per HTTP method using model options.
699
+
700
+ 📂 src/models/Fruit.js
701
+ ```js
702
+ Fruit.options = {
703
+ ...
704
+
705
+ // Auto-endpoint configuration by HTTP method
706
+ defaultEndpoint: {
707
+ GET: true, // Enable auto-generated GET endpoint
708
+
709
+ POST: {
710
+ allow: true,
711
+ jwt: {
712
+ allow: true,
713
+ broken_role: [
714
+ { role: [5, 6] },
715
+ ],
716
+ },
717
+ },
718
+
719
+ PATCH: {
720
+ allow: true,
721
+ jwt: {
722
+ allow: true,
723
+ broken_role: [
724
+ { role: [5, 6, 9] },
725
+ { department: "IT" },
726
+ ],
727
+ },
728
+ },
729
+
730
+ DELETE: false, // Disable auto-generated DELETE endpoint
731
+ },
732
+
733
+ ...
734
+ };
735
+ ```
736
+
737
+ **Use cases**
738
+
739
+ - Fine-grained access control per HTTP method
740
+ - Different role requirements for POST, PATCH, etc.
741
+ - Combine role-based and attribute-based conditions
742
+
743
+ ### 3. Endpoint-Level Configuration (Credentials Middleware) - Priority 1
744
+
745
+ For maximum flexibility, you can define Broken Role rules directly on a specific endpoint using the Credentials middleware.
746
+
747
+ 📂 endpoints/custom-fruit-endpoints.js
748
+ ```js
749
+ const { Fruit } = require("@/models/Fruit");
750
+
751
+ endpoint.delete(
752
+ "/destroy-fruit-by-id/:id",
753
+ Credentials([{ role: [5, 9] }]),
754
+ async (req, res) => {
755
+
756
+ // Only JWT tokens with role level 5 or 9 are allowed
757
+
758
+ const deleted = await Fruit.destroy({
759
+ where: {
760
+ id: req.params.id,
761
+ },
762
+ });
763
+
764
+ console.log("result:", deleted);
765
+
766
+ // @response
767
+ }
768
+ );
769
+ ```
770
+
771
+ **Use cases**
772
+
773
+ - One-off or custom endpoints
774
+ - Highly specific authorization rules
775
+ - Override global or model-level behavior when necessary
776
+
777
+ ## Supported Basic & Operators Usage
778
+
779
+ The JWT Broken Role system supports both basic value matching and advanced operators for flexible authorization rules.
780
+
781
+ | Operator | Meaning | Description |
782
+ |:---------|:-------------------|:--------------------------------------------------------------|
783
+ | $eq | equal | Matches when the value is equal |
784
+ | $ne | not equal | Matches when the value is not equal |
785
+ | $in | value IN array | Matches when the value exists in the specified array |
786
+ | $not | value NOT IN array | Matches when the value does not exist in the specified array |
787
+ | $regex | regex match | Matches using a regular expression |
788
+ | $fn | custom function | Matches using a custom evaluation function |
789
+
790
+ ## Evaluation Logic (Very Important !)
791
+ ```js
792
+ [
793
+ { rule1 AND rule1 },
794
+ { rule2 AND rule2 }
795
+ ]
796
+
797
+ OR
798
+ ```
799
+
800
+ ## Basic Usage for Examples :
801
+
802
+ ```js
803
+ Credentials([
804
+ { role: [9] }, // Only role check
805
+ { email: 'a@b.com' }, // OR email
806
+ ])
807
+
808
+ // Common Matching Patterns
809
+ { role: [1, 2, 3] } // IN
810
+ { role: 1 } // Equal
811
+ { email: 'a@b.com' } // Equal
812
+ { department: 'IT' } // Equal
813
+ { status: ['active'] } // Dynamic key
814
+ ```
815
+
816
+ ## Operators Usage for Examples :
817
+
818
+ ```js
819
+ // Equal with Role
820
+ Credentials([
821
+ {
822
+ role: { $eq: [1, 2, 5] }
823
+ }
824
+ ])
825
+
826
+ // Not Equal with Role
827
+ Credentials([
828
+ {
829
+ role: { $ne: [0, 3] }
830
+ }
831
+ ])
832
+
833
+ // Regex with Email domain
834
+ Credentials([
835
+ {
836
+ email: { $regex: /@company\.com$/ }
837
+ }
838
+ ])
839
+
840
+ // IN with Role
841
+ Credentials([
842
+ {
843
+ role: { $in: [1, 2, 4] }
844
+ }
845
+ ])
846
+
847
+ // NOT IN with Role
848
+ Credentials([
849
+ {
850
+ role: { $not: [0, 3] }
851
+ }
852
+ ])
853
+
854
+ // Multiple OR rules
855
+ Credentials([
856
+ {
857
+ role: { $in: [1] },
858
+ email: 'john.doe@company.com'
859
+ },
860
+ // OR
861
+ {
862
+ role: { $in: [4] },
863
+ email: { $regex: /@company\.com$/ }
864
+ },
865
+ ])
866
+
867
+ // Custom Function
868
+ Credentials([
869
+ {
870
+ role: {
871
+ $fn: (value, user) => value >= 4 && user.department === 'IT'
872
+ }
873
+ }
874
+ ])
875
+ ```
876
+
877
+ # Helpers
878
+
879
+ The `helpers` keep the files of functions for process specific something in the project. So, you might create the `helpers` in path `src/helpers` folder.
880
+
881
+ ```sh
882
+ $ beech make helperName --helper
883
+ ```
884
+
885
+ ***For Example :***
886
+
887
+ 📂 helpers/TextEditor.js
888
+ ```js
889
+ module.exports = {
890
+
891
+ textUpperCase(text) {
892
+ return text.toUpperCase();
893
+ },
894
+
895
+ textTrim(text) {
896
+ return text.trim();
897
+ },
898
+
899
+ ...
900
+
901
+ };
902
+ ```
903
+
904
+ # Authentication (passport-jwt)
905
+
906
+ Passport is authentication middleware for Node. It is designed to serve a singular purpose: authenticate requests. When writing modules, encapsulation is a virtue, so Passport delegates all other functionality to the application. This separation of concerns keeps code clean and maintainable, and makes Passport extremely easy to integrate into an application.
907
+
908
+ ### Passport-jwt Initialization
909
+
910
+ ```sh
911
+ $ beech passport init
912
+ ```
913
+
914
+ After passport initialized the `passport.config.js` it's appeared
915
+
916
+ 📂 passport.config.js
917
+ ```js
918
+ module.exports = {
919
+ // Allow for using passport-jwt
920
+ jwt_allow: true,
921
+
922
+ // custom authenticaiton endpoint name, default `/authentication`
923
+ auth_endpoint: "",
924
+
925
+ // your jwt secret key
926
+ secret: "your_jwt_secret",
927
+
928
+ // token expiry time (seconds), default 86400 sec. it's expired in 24 hr.
929
+ token_expired: 86400,
930
+
931
+ // Allow for using global jwt broken role
932
+ jwt_broken_role: [
933
+ // { role: [1, 2, 9] },
934
+ ],
935
+
936
+ model: {
937
+ // Main sql connection name. You must make sure connection name like inside `app.config.js` file and choose one connection name.
938
+ name: "default_db",
939
+
940
+ // table name of users store, default table `users`
941
+ table: "",
942
+
943
+ // secret user store field for authenticate, default field `username` and `password`
944
+ username_field: "",
945
+ password_field: "",
946
+
947
+ // JWT playload data, You can add it. Example: ["name", "email", ...]
948
+ fields: [],
949
+
950
+ // Other fields add for authentication.
951
+ guard: {
952
+ // Basic guard field, Example: ["pin", "hint", "2fa"]
953
+ guard_field: [],
954
+
955
+ // Advanced guard jwt request (needed some logical from front-end)
956
+ advanced_guard: {
957
+ allow: false,
958
+ entity: "", // default entity `timing`
959
+ secret: "top_secret",
960
+ time_expired: {
961
+ minutes: 1, // should length [0-60]
962
+ seconds: 0, // should length [0-60]
963
+ },
964
+ },
965
+ },
966
+ },
967
+
968
+ // Allow for using request with app_key entity (Every request must be using the app_key entity in headers)
969
+ app_key_allow: false
970
+
971
+ ...
972
+
973
+ };
974
+ ```
975
+ ### Request Token
976
+ **Authentication structure :** Simple ``users`` table:
977
+ ```
978
+ ==============================================================
979
+ | id | username | password | name | email |
980
+ --------------------------------------------------------------
981
+ | 1 | bombkiml | secret | bombkiml NC. | bomb@bomb.com |
982
+ | 2 | johnson | secret | johnson BA. | john@bomb.com |
983
+ ```
984
+
985
+ When you config passport with ```users``` table already. You will got Auth endpoint in available.
986
+ ```js
987
+ POST: "/authentication" // Request token
988
+ POST: "/authentication/refresh" // Request refresh token
989
+ POST: "/authentication/create" // Create new Auth data
990
+ PATCH: "/authentication/update/:id" // Update old Auth data (needed user id)
991
+ ```
992
+
993
+ ***XHR Example :***
994
+
995
+ ```js
996
+ // Request with body for gether Token
997
+ POST: "/authentication"
998
+ payload: {
999
+ username: "bombkiml",
1000
+ password: "secret"
1001
+ }
1002
+
1003
+ // Request with header for refresh token
1004
+ POST: "/authentication/refresh"
1005
+ headers: Authorization: Bearer <your_token>
1006
+
1007
+ // Request with body for Create Auth data
1008
+ POST: "/authentication/create"
1009
+ payload: {
1010
+ username: "add_new_username",
1011
+ password: "add_new_secret",
1012
+ name: "add_new_my_name",
1013
+ email: "add_new_email"
1014
+ }
1015
+
1016
+ // Request with body for Update Auth data
1017
+ PATCH: "/authentication/update/1"
1018
+ headers: Authorization: Bearer <your_token>
1019
+ payload: {
1020
+ username: "update_bombkiml",
1021
+ password: "update_secret",
1022
+ name: "update_my_name",
1023
+ email: "my_update_email@bomb.com"
1024
+ }
1025
+ ```
1026
+
1027
+ # Beech Guard
1028
+ You can easy using 2 Factor authenticate with ```guard_field``` inside ```passport.config.js``` file and add your Guard field ex: ```2fa``` field for Authenticate Conditions.
1029
+
1030
+ ## # Guard (2FA, Other)
1031
+
1032
+ 📂 passport.config.js
1033
+ ```js
1034
+ module.exports = {
1035
+ ...
1036
+
1037
+ guard: {
1038
+ // Other fields add for authenticate, exmaple ["pin", "hint", "2fa"]
1039
+ guard_field: ["2fa"], 👈 // your feild guard. (Disabled to remove it.)
1040
+
1041
+ ...
1042
+ },
1043
+
1044
+ ...
1045
+
1046
+ }
1047
+ ```
1048
+
1049
+ ## # Beech Advanced Guard (Timing)
1050
+ Advance Guard for Protection your Endpoint with Timing. You can allow in object ```advance_guard``` inside ```passport.config.js``` file. So let's go add your Advance Guard Configuration.
1051
+
1052
+ 📂 passport.config.js
1053
+ ```js
1054
+ module.exports = {
1055
+ ...
1056
+
1057
+ guard: {
1058
+ ...
1059
+
1060
+ // Advanced guard to Request (Needed some logical from front-end)
1061
+ advanced_guard: {
1062
+ allow: false, 👈 // advanced guard allow for All Endpoint.
1063
+ entity: "", // default entity `timing`
1064
+ secret: "your_advance_guard_secret",
1065
+ time_expired: {
1066
+ minutes: 1, // should length [0-60]
1067
+ seconds: 0, // should length [0-60]
1068
+ },
1069
+ },
1070
+ },
1071
+
1072
+ ...
1073
+
1074
+ }
1075
+
1076
+ ```
1077
+
1078
+ <b>After configure</b>, You must add some logic in your front-end like this.
1079
+
1080
+ Before add logic, We needed [```beech-auth0```](https://github.com/bombkiml/beech-auth0) and [```moment.js```](https://momentjs.com) for apply in Policy.
1081
+
1082
+ ```sh
1083
+ # NPM
1084
+ $ npm install --save beech-auth0 moment
1085
+
1086
+ # Yarn
1087
+ $ yarn add beech-auth0 moment
1088
+ ```
1089
+ Now! you can add some logic like this.
1090
+
1091
+ - Import packages
1092
+
1093
+ ```js
1094
+ // CommonJS
1095
+ const { Auth0 } = require("beech-auth0");
1096
+ const moment = require("moment");
1097
+
1098
+ // ES6
1099
+ import { Auth0 } from "beech-auth0";
1100
+ import moment from "moment";
1101
+ ```
1102
+
1103
+ - Get unix time with momentJS
1104
+
1105
+ ```js
1106
+ // Get UNIX TIME with moment
1107
+ let unix_time = moment().unix();
1108
+ ```
1109
+
1110
+ - Get hashing with Beech Auth0
1111
+
1112
+ ```js
1113
+ // Auth0 Policy.
1114
+ Auth0(unix_time, 'your_advance_guard_secret', (error, hashing) => {
1115
+
1116
+ // Your XHR request for All Endpoint.
1117
+ POST: "/authentication"
1118
+ headers: { timing: hashing } 👈 // Assign advance guard entity to headers with callback hashing.
1119
+
1120
+ });
1121
+
1122
+ ```
1123
+
1124
+ ## # Beech User Authentication Managements ###
1125
+ You can easy management `users` data with Beech, Only ```Store, Update``` NO ```Delete```, Anything you can make DELETE endpoint by yourself
1126
+
1127
+ ```js
1128
+ const { Store, Update } = require("beech-api");
1129
+ ```
1130
+
1131
+ - ***Store*** users data with ``Store()``
1132
+ ```js
1133
+ // prepare data for store users
1134
+ var data = {
1135
+ username: "bombkiml",
1136
+ password: "secret",
1137
+ name: "bombkiml nc.",
1138
+ email: "bomb@bomb.com"
1139
+ }
1140
+
1141
+ Store(data, (err, stored) => {
1142
+ if (err) throw err;
1143
+
1144
+ // response affected data
1145
+ console.log(stored.insertId, stored.affectedRows);
1146
+
1147
+ });
1148
+ ```
1149
+
1150
+ - ***Update*** users data with ``Update()``
1151
+ ```js
1152
+ // prepare data for update users
1153
+ var data = {
1154
+ password: "new_secret",
1155
+ name: "bombkiml NC.",
1156
+ email: "bombkiml@bomb.com"
1157
+ }
1158
+
1159
+ Update(data, id, (err, updated) => {
1160
+ if (err) throw err;
1161
+
1162
+ // response affected data
1163
+ console.log(updated.updateId, updated.affectedRows);
1164
+
1165
+ });
1166
+ ```
1167
+
1168
+ # Beech with Official Strategy
1169
+
1170
+ Latest supported with ``Google`` and ``Facebook`` Strategy.
1171
+
1172
+
1173
+ ## # Google Strategy
1174
+
1175
+
1176
+ The Google OAuth 2.0 authentication strategy authenticates users using a Google account and OAuth 2.0 tokens. The strategy requires a verify callback, which accepts these credentials and calls done providing a user, as well as options specifying a client ID, client secret, and callback URL.
1177
+
1178
+ Before your application can make use of Sign In With Google, you must register your app with Google. This can be done in the [APIs & Services](https://console.cloud.google.com/apis) page of the [Google Cloud Platform console.](https://console.cloud.google.com/) Once registered, your app will be issued a client ID and secret which will be used in the strategy configuration.
1179
+
1180
+ Go to open file ``passport.config.js`` and go to ``google strategy`` then turn allow Google Strategy is ``allow: true`` something like this.
1181
+
1182
+ 📂 passport.config.js
1183
+ ```js
1184
+ ...
1185
+
1186
+ strategy: {
1187
+
1188
+ google: {
1189
+
1190
+ // Allow for using google strategy
1191
+ allow: true,
1192
+
1193
+ // Authen profile store fields available: `google_id`, `name`, `email`, `photos`, `locate`
1194
+ local_profile_fields: {
1195
+ google_id: "google_id", // Google ID field, default field name: `google_id`
1196
+ name: "your_name_field",
1197
+ email: "your_email_field",
1198
+ photos: "your_profile_url_field",
1199
+ locate: "" // If you not store set to null or remove it.
1200
+ },
1201
+ // Google development Credentials OAuth 2.0 Client IDs
1202
+ client_id: "GOOGLE_CLIENT_ID",
1203
+ client_secret: "GOOGLE_CLIENT_SECRET",
1204
+ // Callback endpoint default `/google/callback`
1205
+ callbackURL: "",
1206
+ // Failure redirect to your route
1207
+ failureRedirect: "/login"
1208
+ }
1209
+ }
1210
+
1211
+ ...
1212
+ ```
1213
+
1214
+ The above code is a configures and registers the Google Strategy.
1215
+
1216
+ - ``allow`` : Turn on/off the Google Strategy config type of ``boolean`` switch by ``true/false``.
1217
+ - ``google_id`` : Local Google ID field for store Google ID in my local database default field is ``google_id``.
1218
+ - ``local_profile_fields`` : Local Profile fields for store Google user details.
1219
+ - ``client_id`` and ``client_secret`` : The options to the Google Strategy constructor must include a ``clientID`` and ``clientSecret``, the values of which are set to the client ID and secret that were obtained when registering your application.
1220
+ - ``callbackURL`` : When registering your application. A callbackURL must also be included. Google will redirect users to this location after they have authenticated.
1221
+ - ``failureRedirect`` : When registering your application somthing failure it's redirect to that.
1222
+
1223
+ Place a button on the application's login page, prompting the user to sign in with Google.
1224
+
1225
+ ```html
1226
+ <a href="/authentication/google" class="button">Sign in with Google</a>
1227
+ ```
1228
+
1229
+ ❓ **Note:** The URL "``/authentication``" will be follow by ``auth_endpoint`` when you custom it.
1230
+
1231
+
1232
+ ## # Facebook Strategy
1233
+
1234
+
1235
+ Facebook Login allows users to sign in using their Facebook account. Support for Faceboook Login is provided by the ``passport-facebook`` package.
1236
+
1237
+ Before your application can make use of Facebook Login, you must register your app with Facebook. This can be done in the [App dashboard](https://developers.facebook.com/apps) at [Facebook for Developers.](https://developers.facebook.com/) Once registered, your app will be issued an app ID and secret which will be used in the strategy configuration.
1238
+
1239
+ Go to open file ``passport.config.js`` and go to ``facebook strategy`` then turn allow Facebook Strategy is ``allow: true`` something like this.
1240
+
1241
+ 📂 passport.config.js
1242
+ ```js
1243
+ ...
1244
+
1245
+ strategy: {
1246
+
1247
+ facebook: {
1248
+
1249
+ // Allow for using facebook strategy
1250
+ allow: true,
1251
+
1252
+ // Authen profile store fields available: `facebook_id`, `name`, `email`, `photos`, `locate`
1253
+ local_profile_fields: {
1254
+ facebook_id: "facebook_id", // Facebook ID field, default field name: `facebook_id`
1255
+ name: "your_name_field",
1256
+ email: "your_email_field",
1257
+ photos: "your_profile_url_field",
1258
+ locate: "" // If you not store set to null or remove it.
1259
+ },
1260
+ // Facebook development Credentials OAuth 2.0
1261
+ app_id: "FACEBOOK_APP_ID",
1262
+ app_secret: "FACEBOOK_APP_SECRET",
1263
+
1264
+ // You can allow Permissions facebook profile fields. Learn more (https://developers.facebook.com/docs/graph-api/reference/v13.0/user#readperms)
1265
+ // **Update 2024, Now! Facebook requests permission for show Email. Learn more (https://developers.facebook.com/docs/permissions)
1266
+ profileFieldsAllow: [ 'id', 'displayName', 'name', 'photos', 'email', 'location' ], // Default allowed
1267
+
1268
+ // Callback endpoint default `/facebook/callback`
1269
+ callbackURL: "",
1270
+ // Failure redirect to your route
1271
+ failureRedirect: "/login"
1272
+ }
1273
+ }
1274
+
1275
+ ...
1276
+ ```
1277
+
1278
+ The above code is a configures and registers the Facebook Strategy.
1279
+
1280
+ - ``allow`` : Turn on/off the Facebook Strategy config type of ``boolean`` switch by ``true/false``.
1281
+ - ``facebook_id`` : Local Facebook ID field for store Facebook ID in my local database default field is ``facebook_id``.
1282
+ - ``local_profile_fields`` : Local Profile fields for store Facebook user details.
1283
+ - ``app_id`` and ``app_secret`` : The options to the Facebook Strategy must include an app ID and secret. you must register your app with Facebook. This can be done in the [App dashboard](https://developers.facebook.com/apps) at [Facebook for Developers.](https://developers.facebook.com/) Once registered, your app will be issued an ``app ID`` and ``secret`` which will be used in the strategy configuration.
1284
+ - ``profileFieldsAllow`` : Permissions with Facebook Login. You must allow Permissions facebook profile fields: see more (https://developers.facebook.com/docs/graph-api/reference/v13.0/user#readperms)
1285
+ - ``callbackURL`` : When registering your application. A callbackURL must also be included. Facebook will redirect users to this location after they have authenticated.
1286
+ - ``failureRedirect`` : When registering your application somthing failure it's redirect to that.
1287
+
1288
+ Place a button on the application's login page, prompting the user to sign in with Facebook.
1289
+
1290
+ ```html
1291
+ <a href="/authentication/facebook" class="button">Log In With Facebook</a>
1292
+ ```
1293
+
1294
+ ❓ **Note:** The URL "``/authentication``" will be follow by ``auth_endpoint`` when you custom it.
1295
+
1296
+ # CORS Origin & Server Configuration
1297
+ The origin array to the callback can be any value allowed for the origin option of the middleware. Certain CORS requests are considered `complex` and require an initial OPTIONS request (called the `pre-flight request`). You can allowed CORS origin inside file `beech.config.js`
1298
+
1299
+ 📂 beech.config.js
1300
+ ```js
1301
+ module.exports = {
1302
+ defineConfig: {
1303
+ // Base public path when served in development or production.
1304
+ base: process.env.NODE_ENV === "production"
1305
+ ? "/my-api/" // For Production
1306
+ : "/", // For Development
1307
+
1308
+ server: {
1309
+ // Client request allow origin whitelist
1310
+ origin: ["http://example.com", "http://my-webapp:8080", "https://cat.io"],
1311
+ originSensitive: false, // Sensitive with contrasts wording
1312
+
1313
+ // API Request rate limit (Disabled for Remove it.)
1314
+ rateLimit: {
1315
+ windowMs: 15 * 60 * 1000, // 15 minutes
1316
+ limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes).
1317
+ // store: ... , // Redis, Memcached, etc.
1318
+ // See more: https://www.npmjs.com/package/express-rate-limit#Configuration
1319
+ },
1320
+
1321
+ // API Duplicate Request (Disabled for Set expiration to 0 zero.)
1322
+ duplicateRequest: {
1323
+ expiration: 500, // Can't duplicate request for 5 milliseconds each IP requests per `window`
1324
+ },
1325
+
1326
+ payload: {
1327
+ // The limit of request body size, json default "100KB", urlencoded default "100KB". Learn more: https://expressjs.com/en/4x/api.html#express.json
1328
+ json: {
1329
+ limit: "100KB", // default: "100KB"
1330
+ },
1331
+ urlencoded: {
1332
+ limit: "100KB", // default: "100KB"
1333
+ extended: true, // default: true (reccomended: true)
1334
+ },
1335
+ file: {
1336
+ uploadAllowMethod: ["POST", "PATCH", "PUT"], // Only apply file upload limit for POST, PATCH, PUT method.
1337
+ allowedTypes: ["image/jpeg", "image/png", "application/pdf"], // Example: Allow only JPEG, PNG, and PDF files. Learn more: https://www.digipres.org/formats/mime-types/
1338
+ limit: 5 * 1024 * 1024, // 5MB (default: Infinity)
1339
+ },
1340
+ },
1341
+
1342
+ },
1343
+ },
1344
+ }
1345
+ ```
1346
+
1347
+ ❓ **Note:** When you must to allowed all Origin. You can assign `*` or `[]` null value to `origin` variable.
1348
+
1349
+ ## # Custom Endpoint Specific Rate Limit
1350
+ When you need assign specific request Endpoint with [express-rate-limit](https://www.npmjs.com/package/express-rate-limit), You can managemnet with Beech object ```rateLimit``` for your custom Rate Limit like this.
1351
+
1352
+ ```js
1353
+ const { rateLimit } = require("beech-api").Express;
1354
+
1355
+ // Specific of your rate limit
1356
+ const specificRateLimit1 = rateLimit({
1357
+ windowMs: 5 * 60 * 1000, // 5 minutes
1358
+ limit: 20,
1359
+ // more...
1360
+ });
1361
+
1362
+ // Your Endpoints...
1363
+ endpoint.get("/banana", specificRateLimit1, (req, res) => {
1364
+ ...
1365
+ });
1366
+
1367
+ ...
1368
+ ```
1369
+
1370
+ ## # Custom Endpoint Specific Slow Down
1371
+ **DON'T DO IT.** &nbsp; Because it's annoying to users.
1372
+
1373
+ When you need assign specific request Endpoint with [express-slow-down](https://www.npmjs.com/package/express-slow-down), You can managemnet with Beech object ```slowDown``` for your custom Slow Down like this.
1374
+
1375
+ ```js
1376
+ const { slowDown } = require("beech-api").Express;
1377
+
1378
+ // Specific of your slow down
1379
+ const specificSlowDown1 = slowDown({
1380
+ windowMs: 15 * 60 * 1000, // 15 minutes
1381
+ delayAfter: 5, // Allow 5 requests per 15 minutes.
1382
+ delayMs: (hits) => hits * 100, // Add 100 ms of delay to every request after the 5th one.
1383
+ // more...
1384
+
1385
+ /**
1386
+ * So:
1387
+ *
1388
+ * - requests 1-5 are not delayed.
1389
+ * - request 6 is delayed by 600ms
1390
+ * - request 7 is delayed by 700ms
1391
+ * - request 8 is delayed by 800ms
1392
+ *
1393
+ * and so on. After 15 minutes, the delay is reset to 0.
1394
+ */
1395
+ });
1396
+
1397
+ // Your Endpoints...
1398
+ endpoint.get("/banana", specificSlowDown1, (req, res) => {
1399
+ ...
1400
+ });
1401
+
1402
+ ...
1403
+ ```
1404
+
1405
+ ## # Custom Endpoint Specific Duplicate Request
1406
+ This middleware to Limit each IP duplicated requests per window.
1407
+
1408
+ When you need assign specific request Endpoint with duplicate request use [express-duplicate-request](https://github.com/bombkiml/express-duplicate-request), You can managemnet with Beech object ```duplicateRequest``` for your custom Duplicate Request like this.
1409
+
1410
+ ```js
1411
+ const { duplicateRequest } = require("beech-api").Express;
1412
+
1413
+ // Specific of your duplicate request
1414
+ const specificDup1 = duplicateRequest({
1415
+ expiration: 500, // Can't duplicate request for 5 milliseconds, Should 0 to disabled
1416
+ // more...
1417
+ });
1418
+
1419
+ // Your Endpoints...
1420
+ endpoint.get("/banana", specificDup1, (req, res) => {
1421
+ ...
1422
+ });
1423
+
1424
+ ...
1425
+ ```
1426
+
1427
+ # Databases managements
1428
+
1429
+ ## # Migrations & Seeder
1430
+
1431
+ Just like you use Git / SVN to manage changes in your source code, you can use migrations to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.
1432
+
1433
+ You will need [Sequelize CLI.](https://github.com/sequelize/cli) The CLI ships support for [migrations](https://sequelize.org/v5/manual/migrations.html) and project.
1434
+
1435
+ ## # Usage
1436
+
1437
+ To create an empty project you will need to execute `init` command
1438
+
1439
+ ```sh
1440
+ $ npx sequelize-cli init
1441
+ ```
1442
+
1443
+ This will create following folders inside `databases` folder.
1444
+
1445
+ - `config`, contains config file, which tells CLI how to connect with database.
1446
+ - `models`, contains all models for your project.
1447
+ - `migrations`, contains all migration files.
1448
+ - `seeders`, contains all seed files.
1449
+
1450
+ ## # Configuration
1451
+
1452
+ Before continuing further we will need to tell CLI how to connect to database. To do that let's open default config file `databases/config/database.json` It looks something like this:
1453
+
1454
+ ```json
1455
+ {
1456
+ "development": {
1457
+ "username": "root",
1458
+ "password": null,
1459
+ "database": "database_development",
1460
+ "host": "127.0.0.1",
1461
+ "port": 3306, // IF your another port
1462
+ "dialect": "mysql"
1463
+ },
1464
+ "test": {
1465
+ "username": "root",
1466
+ "password": null,
1467
+ "database": "database_test",
1468
+ "host": "127.0.0.1",
1469
+ "dialect": "mysql"
1470
+ },
1471
+ "production": {
1472
+ "username": "root",
1473
+ "password": null,
1474
+ "database": "database_production",
1475
+ "host": "127.0.0.1",
1476
+ "dialect": "mysql"
1477
+ }
1478
+ }
1479
+ ```
1480
+
1481
+ ❓ **Note:** The database connect default port 3306 if you another port you can add object ``port`` in config.
1482
+
1483
+ ❓ **Note:** If your database doesn't exists yet, you can just call `npx sequelize-cli db:create` command. With proper access it will create that database for you.
1484
+
1485
+ ## # Creating first Migrations
1486
+
1487
+ Create `model` use `model:generate` command. This command requires two options.
1488
+
1489
+ - `--name`, Name of the model
1490
+ - `--attributes`, List of model attributes
1491
+
1492
+ Let's create a model name example `User`. See more about of [Datatypes](https://sequelize.org/v5/manual/data-types.html)
1493
+
1494
+ ```sh
1495
+ $ npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string,birhday:date
1496
+ ```
1497
+
1498
+ ## # Migrations Up and Down
1499
+
1500
+ Until this step, we haven't inserted anything into the database. We have just created required model and migration files for our first model User.
1501
+
1502
+ - **Migrate Up** : you can create that table in database you need to run db:migrate command.
1503
+
1504
+ ```sh
1505
+ $ npx sequelize-cli db:migrate
1506
+ ```
1507
+
1508
+ - **Migrate Down** : you can use `db:migrate:undo`, this command will revert most recent migration.
1509
+ ```sh
1510
+ // Step to undo
1511
+ $ npx sequelize-cli db:migrate:undo
1512
+
1513
+ // All to undo
1514
+ $ npx sequelize-cli db:migrate:undo:all
1515
+
1516
+ ```
1517
+
1518
+ ## # Creating First Seeder
1519
+
1520
+ To manage all data migrations you can use seeders. Seed files are some change in data that can be used to populate database table with sample data or test data.
1521
+
1522
+ Let's create a seed file which will add a demo user to our User table.
1523
+
1524
+ ```sh
1525
+ $ npx sequelize-cli seed:generate --name user
1526
+ ```
1527
+
1528
+ ## # Seeder Up and Down
1529
+
1530
+ In last step you have create a seed file. It's still not committed to database. To do that we need to run a simple command.
1531
+
1532
+ - **Seed Up** : you can execute that seed file and you will have a user inserted into `User` table.
1533
+
1534
+ ```sh
1535
+ $ npx sequelize-cli db:seed:all
1536
+ ```
1537
+
1538
+ - **Seed Down** : seeders can be undone if they are using any storage. There are two commands available for that:
1539
+
1540
+ If you wish to undo most recent seed
1541
+
1542
+ ```sh
1543
+ $ npx sequelize-cli db:seed:undo
1544
+ ```
1545
+
1546
+ If you wish to undo a specific seed
1547
+
1548
+ ```
1549
+ $ npx sequelize-cli db:seed:undo --seed <seederName>
1550
+ ```
1551
+
1552
+ If you wish to undo all seeds
1553
+
1554
+ ```sh
1555
+ $ npx sequelize-cli db:seed:undo:all
1556
+ ```
1557
+
1558
+ # Testing
1559
+
1560
+ Test using [Jest](https://jestjs.io/en/) for testing the project. Jest is a delightful JavaScript Testing Framework with a focus on simplicity. Learn more [Jest docs](https://jestjs.io/docs/en/getting-started.html)
1561
+
1562
+ So, When you make the new endpoints it's automatic create test file end with `.spec.js` in `__test__` folder with constant `baseUrl` variable and `axios` package.
1563
+
1564
+ ***For Example :***
1565
+
1566
+ 📂 \_\_test\_\_/unit/endpoints/fruit-endpoints.spec.js
1567
+ ```js
1568
+ const endpoint = baseUrl.concat("/fruit");
1569
+
1570
+ describe("Test endpoint : " + endpoint, () => {
1571
+ it("Truthy!", () => {
1572
+ expect("/fruit").toBeTruthy();
1573
+ });
1574
+
1575
+ it("Respond with basic GET status code 200", (done) => {
1576
+ axios.get(endpoint).then((res) => {
1577
+ expect(200).toEqual(res.data.code);
1578
+ done();
1579
+ });
1580
+ });
1581
+ });
1582
+ ```
1583
+
1584
+ # Building for Production
1585
+
1586
+ The Beech API build system is designed to secure your source code without sacrificing performance.
1587
+
1588
+ To start the build process, run the following command from your project root
1589
+
1590
+ ```sh
1591
+ $ npm run build
1592
+ # OR
1593
+ $ yarn build
1594
+ ```
1595
+
1596
+ ❓ **Note:** This command triggers ```beech-service build``` as defined in your package.json.
1597
+
1598
+ ### # What happens during Build ?
1599
+ The build engine performs the following automated steps:
1600
+
1601
+ - **Scanning**: It scans for all .js files in src/ (endpoints, models, helpers) and configuration files.
1602
+
1603
+ - **Entry Point Generation**: It retrieves the core engine template (beech.txt) and converts it into a secured server.js in the output folder.
1604
+
1605
+ - **Compilation**: Files are minified to reduce size.
1606
+
1607
+ - **Obfuscation**:
1608
+
1609
+ - Variables and function names are renamed.
1610
+ - Strings are Base64 encoded.
1611
+ - Performance remains 100% because control-flow logic is preserved.
1612
+
1613
+ - **Distribution**: All protected files are placed in the ```./dist``` directory.
1614
+
1615
+ ### # Deployment Structure ?
1616
+ After the build is complete, your ./dist folder will look like this:
1617
+
1618
+ ```sh
1619
+ dist/
1620
+ ├── src/
1621
+ │ ├── endpoints/ (Obfuscated)
1622
+ │ ├── models/ (Obfuscated)
1623
+ │ ├── helpers/ (Obfuscated)
1624
+ │ └── etc/ (Obfuscated)
1625
+ ├── server.js (Main entry point)
1626
+ ├── app.config.js (Obfuscated)
1627
+ ├── beech.config.js (Obfuscated)
1628
+ ├── global.config.js (Obfuscated)
1629
+ └── package.json (Copied for dependency management)
1630
+ ```
1631
+
1632
+ ## # Starting the Production Server ?
1633
+ To run your application in production:
1634
+
1635
+ - Upload the contents of the dist folder to your server.
1636
+
1637
+ - Install only production dependencies:
1638
+ ```sh
1639
+ npm install --production
1640
+ ```
1641
+
1642
+ # Implementation
1643
+
1644
+ ## # Implement with [Docker](https://www.docker.com)
1645
+
1646
+ [Docker](https://www.docker.com) is an open platform for developing, shipping, and running applications. Docker enables you to separate your applications from your infrastructure so you can deliver software quickly.
1647
+
1648
+ - ### **Create Dockerfile**
1649
+
1650
+ Docker builds images automatically by reading the instructions from a Dockerfile -- a text file that contains all commands, in order, needed to build a given image. A Dockerfile adheres to a specific format and set of instructions which you can find at [Dockerfile reference](https://docs.docker.com/engine/reference/builder/).
1651
+
1652
+ 📂 Dockerfile
1653
+ ```js
1654
+ FROM node:18-alpine
1655
+ ENV NODE_ENV=production
1656
+ WORKDIR /usr/src/api
1657
+ COPY ["package.json", "package-lock.json*", "./"]
1658
+ RUN npm install --production --silent && mv node_modules .
1659
+ COPY . .
1660
+ EXPOSE 9000
1661
+ CMD ["node", "server.js"]
1662
+ ```
1663
+
1664
+ - ### **Docker build image**
1665
+
1666
+ The docker build command builds an image from a Dockerfile and a context. The build’s context is the set of files at a specified location ```PATH``` or ```URL```. The PATH is a directory on your local filesystem. The URL is a Git repository location.
1667
+
1668
+ ```sh
1669
+ $ docker build -t <imageName> .
1670
+ ```
1671
+
1672
+ ❓ **Note:** You can specify a repository and tag at which to save the new image : ``` $ docker build -t <imageName>:<tags> . ```
1673
+
1674
+ - ### **Run docker**
1675
+
1676
+ After create ``image`` you can run docker engine following :
1677
+
1678
+ - ### **Docker Container (Standalone)**
1679
+ ```sh
1680
+ $ docker run -d -p 9000:9000 --name <containerName> <imageName>
1681
+ ```
1682
+
1683
+ - ### **Create Docker Swarm (Cluster)**
1684
+ ```sh
1685
+ # Initiate swarm
1686
+ $ docker swarm init
1687
+
1688
+ # Run docker service
1689
+ $ docker service create --replicas <instances> --name <containerName> --publish 9000:9000 <imageName>
1690
+ ```
1691
+
1692
+ ## # Implement with [PM2](https://pm2.keymetrics.io/)
1693
+ [PM2](https://pm2.keymetrics.io/) is a daemon process manager that will help you manage and keep your application online. Getting started with PM2 is straightforward, it is offered as a simple and intuitive CLI, installable via [NPM](https://www.npmjs.com/).
1694
+
1695
+ ```sh
1696
+ # Start service as standalone
1697
+ $ pm2 start server.js --name <serviceName>
1698
+
1699
+ # OR
1700
+
1701
+ # Start service as cluster mode
1702
+ $ pm2 start server.js --name <serviceName> -i <instances>
1703
+ ```
1704
+
1705
+ # Development
1706
+
1707
+ Want to contribute or join for great job!, You can contact to me via
1708
+
1709
+ - GitHub: [bombkiml/beech-api - issues](https://github.com/bombkiml/beech-api/issues)
1710
+ - E-mail: nattapat.jquery@gmail.com
1711
+ - Facebook: [https://www.facebook.com/bombkiml](https://www.facebook.com/bombkiml)
1712
+
1713
+ # License
1714
+
1715
+ The Beech API framework is open-sourced software licensed under the [MIT license.](https://opensource.org/licenses/MIT)