create-sip 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,176 +37,3 @@ Options:
37
37
  Express API
38
38
  ❯ Cancel
39
39
  ```
40
-
41
- ## Express API
42
-
43
- Key generation:
44
-
45
- ```bash
46
- node op key:generate
47
- ```
48
-
49
- Afte project generation, you have an config/default.json file. If you want generate a new file, delete the config/default.json file and run next command:
50
-
51
- ```bash
52
- node op conf:generate
53
- ```
54
-
55
- Create model:
56
-
57
- ```bash
58
- node op create model <name>
59
- ```
60
-
61
- Create controller:
62
-
63
- ```bash
64
- node op create controller <name>
65
- ```
66
-
67
- Exmple:
68
-
69
- ```bash
70
- node op create model employee
71
- node op create controller employee
72
- ```
73
-
74
- ### Database
75
-
76
- Default database type is sqlite :memory:. If you want to use another database, edit the config/default.json file. For example SQLite:
77
-
78
- ```json
79
- {
80
- "app": {
81
- "port": 8000,
82
- "key": "",
83
- "log": "console.log"
84
- },
85
- "db": {
86
- "dialect": "sqlite",
87
- "host": "127.0.0.1",
88
- "name": "",
89
- "user": "",
90
- "pass": "",
91
- "path": "database.sqlite"
92
- }
93
- }
94
- ```
95
-
96
- Must be set the database path in the config/default.json file.
97
-
98
- ### Default admin user
99
-
100
- Generate admin user:
101
-
102
- ```bash
103
- node op admin:generate
104
- ```
105
-
106
- ### Copy default config file
107
-
108
- Copy **config/default.json.example** to **config/default.json** file.
109
-
110
- Command:
111
-
112
- ```bash
113
- node op conf:generate
114
- ```
115
-
116
- ### Database import
117
-
118
- Load data from JSON or CSV file.
119
-
120
- Examples:
121
-
122
- ```bash
123
- node op db:import thing somethings.json
124
- node op db:import thing somethings.csv
125
- node op db:import thing somethings.csv :
126
- node op db:import thing somethings.csv ";"
127
- node op db:import thing somethings.csv ,
128
- ```
129
-
130
- The last option is the separator.
131
-
132
- For example JSON file:
133
-
134
- employees.json:
135
-
136
- ```json
137
- [
138
- { "id": 1, "name": "Tom Large" },
139
- { "id": 2, "name": "Jack Small" }
140
- ]
141
- ```
142
-
143
- The default separator is comma.
144
-
145
- ```cmd
146
- node op db:import employee employees.json
147
- ```
148
-
149
- For example CSV file:
150
-
151
- employees.csv:
152
-
153
- ```csv
154
- id,name
155
- 1,Joe Kitin
156
- 2,Peter Fall
157
- ```
158
-
159
- If you have colon separator, use sep parameter.
160
-
161
- ```csv
162
- id:name
163
- 1:Joe Kitin
164
- 2:Peter Fall
165
- ```
166
-
167
- ```cmd
168
- node op db:import employee employees.csv --sep :
169
- ```
170
-
171
- If the file has semicolon separator, use sep parameter, for example:
172
-
173
- ```csv
174
- id;name
175
- 1;Joe Kitin
176
- 2;Peter Fall
177
- ```
178
-
179
- Use next command:
180
-
181
- ```cmd
182
- node op db:import employee employees.csv --sep ";"
183
- ```
184
-
185
- ## Migration
186
-
187
- Generate migration:
188
-
189
- ```bash
190
- node op make:migration <name>
191
- ```
192
-
193
- Run migration:
194
-
195
- ```bash
196
- node op migration:run
197
- ```
198
-
199
- Reset database:
200
-
201
- ```bash
202
- node op migration:reset
203
- ```
204
-
205
- Rollback migrations:
206
-
207
- ```bash
208
- node op migration:rollback
209
- node op migration:rollback --step 2
210
- ```
211
-
212
- The steop option is the number of migrations to rollback.
package/create-sip.js CHANGED
@@ -61,7 +61,7 @@ const questions = [
61
61
  },
62
62
  {
63
63
  title: 'Express API',
64
- description: 'Express API with simple Sequelize and ES modules',
64
+ description: 'Express API using Sequelize and ES modules',
65
65
  value: 'expressapi'
66
66
  },
67
67
  {
@@ -0,0 +1,10 @@
1
+ APP_PORT=8000
2
+ APP_KEY=
3
+ APP_LOG=console.log
4
+
5
+ DB_DIALECT=sqlite
6
+ DB_HOST=127.0.0.1
7
+ DB_NAME=
8
+ DB_USER=
9
+ DB_PASS=
10
+ DB_PATH=:memory:
@@ -0,0 +1,7 @@
1
+
2
+ APP_PORT=8000
3
+ APP_KEY=my_secret_key
4
+ APP_LOG=false
5
+
6
+ DB_DIALECT=sqlite
7
+ DB_STORAGE=:memory:
@@ -1,6 +1,6 @@
1
- # sip expressapi sabon
1
+ # sip expressapi template
2
2
 
3
- Express based REST API sablon
3
+ Express based REST API template
4
4
 
5
5
  ## Install
6
6
 
@@ -106,6 +106,28 @@ The keys in the JSON file and the field names in the CSV file must match the mod
106
106
 
107
107
  If the CSV file contains quotation marks, they are automatically removed.
108
108
 
109
+ ## Database synchronization
110
+
111
+ Models and database tables can be synchronized, but this can be dangerous.
112
+
113
+ Database synchronization can be set up in the app/models/modrels.js file. Default values are:
114
+
115
+ ```js
116
+ { alter: true }
117
+ ```
118
+
119
+ This preserves the data and existing structure.
120
+
121
+ Possible values:
122
+
123
+ ```js
124
+ { force: true }
125
+ ```
126
+
127
+ The latter deletes the contents of the database table!
128
+
129
+ If the value is false, there is no synchronization in either case.
130
+
109
131
  ## Migration
110
132
 
111
133
  Generate a migration:
@@ -0,0 +1,17 @@
1
+ import express from 'express'
2
+ import morgan from 'morgan'
3
+ import cors from 'cors'
4
+ import fs from 'fs'
5
+ import router from './routes/api.js'
6
+ import './models/modrels.js'
7
+
8
+ const app = express()
9
+
10
+ const logfile = 'access.log'
11
+ var accessLogStream = fs.createWriteStream(logfile, { flags: 'a' })
12
+ app.use(morgan('dev', { stream: accessLogStream }))
13
+ app.use(cors())
14
+ app.use(express.json())
15
+ app.use('/api', router);
16
+
17
+ export default app
@@ -1,9 +1,8 @@
1
1
  import bcrypt from 'bcryptjs'
2
2
  import jwt from 'jsonwebtoken'
3
3
  import User from '../models/user.js'
4
- import { readJson } from '../../tools/readjson.js'
5
-
6
- const config = await readJson('config/default.json')
4
+ import dotenv from '@dotenvx/dotenvx'
5
+ dotenv.config({ quiet: true })
7
6
 
8
7
  const AuthController = {
9
8
  async register(req, res) {
@@ -47,14 +46,13 @@ const AuthController = {
47
46
  email: req.body.email,
48
47
  password: bcrypt.hashSync(req.body.password)
49
48
  }
50
- await User.create(user)
51
- .then( result => {
52
- res.status(201)
53
- res.json({
54
- succes: true,
55
- data: result
56
- })
49
+ const result = await User.create(user)
50
+
51
+ res.status(201).json({
52
+ succes: true,
53
+ data: result
57
54
  })
55
+
58
56
  },
59
57
  async login(req, res) {
60
58
 
@@ -90,7 +88,7 @@ const AuthController = {
90
88
  }
91
89
  },
92
90
  async tryLogin(req, res, user) {
93
- var token = jwt.sign({ id: user.id }, config.app.key, {
91
+ var token = jwt.sign({ id: user.id }, process.env.APP_KEY, {
94
92
  expiresIn: 86400 //24 óra
95
93
  })
96
94
  res.status(200).json({
@@ -88,7 +88,42 @@ const UserController = {
88
88
  data: userData
89
89
  })
90
90
  },
91
-
91
+ async updatePassword(req, res) {
92
+ var clientError = false;
93
+ try {
94
+ if(!req.body.password ||
95
+ !req.body.password_confirmation) {
96
+ clientError = true
97
+ throw new Error('Error! Bad request data!')
98
+ }
99
+ if(req.body.password != req.body.password_confirmation) {
100
+ clientError = true
101
+ throw new Error('Error! The two password is not same!')
102
+ }
103
+ await UserController.tryUpdatePassword(req, res)
104
+ }catch(error) {
105
+ if (clientError) {
106
+ res.status(400)
107
+ }else {
108
+ res.status(500)
109
+ }
110
+ res.json({
111
+ success: false,
112
+ message: 'Error! The query is failed!',
113
+ error: error.message
114
+ })
115
+ }
116
+ },
117
+ async tryUpdatePassword(req, res) {
118
+ const user = await User.findByPk(req.params.id)
119
+ user.password = bcrypt.hashSync(req.body.password)
120
+ await user.save()
121
+ res.status(200)
122
+ res.json({
123
+ success: true,
124
+ data: user
125
+ })
126
+ }
92
127
  }
93
128
 
94
129
  export default UserController
@@ -1,23 +1,23 @@
1
1
  import Sequelize from 'sequelize'
2
- import { readJson } from '../../tools/readjson.js'
2
+ import dotenv from '@dotenvx/dotenvx'
3
3
 
4
- const config = await readJson('config/default.json')
5
-
6
- if(config.app.log != false) {
7
- var log = console.log
4
+ if (process.env.NODE_ENV === 'test') {
5
+ dotenv.config({ path: '.env.test', quiet: true })
6
+ }else {
7
+ dotenv.config({ quiet: true })
8
8
  }
9
9
 
10
10
  const sequelize = new Sequelize(
11
- config.db.name,
12
- config.db.user,
13
- config.db.pass,
11
+ process.env.DB_NAME,
12
+ process.env.DB_USER,
13
+ process.env.DB_PASS,
14
14
  {
15
- logging: log,
16
- dialect: config.db.dialect,
17
- storage: config.db.path,
18
- host: config.db.host,
15
+ dialect: process.env.DB_DIALECT,
16
+ storage: process.env.DB_STORAGE,
17
+ host: process.env.DB_HOST,
18
+ logging: process.env.APP_LOG === 'true' ? console.log : false,
19
19
  dialectOptions: {}
20
20
  }
21
21
  )
22
-
23
- export default sequelize
22
+
23
+ export default sequelize
@@ -1,23 +1,9 @@
1
- import express from 'express'
2
- import morgan from 'morgan'
3
- import cors from 'cors'
4
- import fs from 'fs'
5
- import router from './routes/api.js'
6
- import { readJson } from '../tools/readjson.js'
7
- import './models/modrels.js'
1
+ import app from './app.js'
2
+ import dotenv from '@dotenvx/dotenvx'
8
3
 
9
- const config = await readJson('config/default.json')
4
+ dotenv.config({ quiet: true })
10
5
 
11
- const app = express()
12
-
13
- const PORT = config.app.port || 8000
14
-
15
- const logfile = 'access.log'
16
- var accessLogStream = fs.createWriteStream(logfile, { flags: 'a' })
17
- app.use(morgan('dev', { stream: accessLogStream }))
18
- app.use(cors())
19
- app.use(express.json())
20
- app.use('/api', router);
6
+ const PORT = process.env.APP_PORT || 8000
21
7
 
22
8
  app.listen(PORT, () => {
23
9
  console.log(`Listening on port: ${PORT}`)
@@ -1,7 +1,6 @@
1
1
  import jwt from 'jsonwebtoken';
2
- import { readJson } from '../../tools/readjson.js'
3
-
4
- const config = await readJson('config/default.json')
2
+ import dotenv from '@dotenvx/dotenvx'
3
+ dotenv.config({ quiet: true })
5
4
 
6
5
  const verifyToken = (req, res, next) => {
7
6
  let authData = req.headers.authorization;
@@ -12,7 +11,7 @@ const verifyToken = (req, res, next) => {
12
11
  }
13
12
  let token = authData.split(' ')[1];
14
13
 
15
- jwt.verify(token, config.app.key, (err, decoded) => {
14
+ jwt.verify(token, process.env.APP_KEY, (err, decoded) => {
16
15
  if(err) {
17
16
  return res.status(401).send({
18
17
  message: "Unauthorized!"
@@ -3,10 +3,12 @@ const router = Router()
3
3
 
4
4
  import AuthController from '../controllers/authController.js';
5
5
  import UserController from '../controllers/userController.js';
6
- import verifyToken from '../middlewares/authjwt.js';
6
+ import verifyToken from '../middleware/authjwt.js';
7
7
 
8
8
  router.post('/register', AuthController.register)
9
9
  router.post('/login', AuthController.login)
10
10
  router.get('/users', [verifyToken], UserController.index)
11
-
11
+ router.get('/users/:id', [verifyToken], UserController.show)
12
+ router.put('/users/:id/password', [verifyToken], UserController.updatePassword)
13
+
12
14
  export default router
@@ -0,0 +1,34 @@
1
+ import { DataTypes } from 'sequelize';
2
+
3
+ async function up({context: QueryInterface}) {
4
+ await QueryInterface.createTable('users', {
5
+ id: {
6
+ allowNull: false,
7
+ autoIncrement: true,
8
+ primaryKey: true,
9
+ type: DataTypes.INTEGER
10
+ },
11
+ name: {
12
+ type: DataTypes.STRING,
13
+ allowNull: false
14
+ },
15
+ email: {
16
+ type: DataTypes.STRING,
17
+ allowNull: true
18
+ },
19
+ password: {
20
+ type: DataTypes.STRING,
21
+ allowNull: false
22
+ },
23
+ roleId: {
24
+ type: DataTypes.INTEGER,
25
+ defaultValue: 0
26
+ }
27
+ });
28
+ }
29
+
30
+ async function down({context: QueryInterface}) {
31
+ await QueryInterface.dropTable('users');
32
+ }
33
+
34
+ export { up, down }
@@ -6,10 +6,22 @@ The app key generated with generate-api-key package.
6
6
 
7
7
  ## Testing
8
8
 
9
- Set in config/default.json file, the db.dialect to sqlite. Set db.path to :memory:
9
+ Run tests:
10
+
11
+ ```cmd
12
+ npm test
13
+ ```
14
+
15
+ The test using the .env.test file and run in the memory database.
16
+
17
+ Tests can be placed in the test directory, where Mocha runs them.
18
+
19
+ ## Development
10
20
 
11
21
  Start the application:
12
22
 
13
23
  ```cmd
14
24
  npm run dev
15
25
  ```
26
+
27
+ Restarting the application when saving is done by nodemon.