Merge pull request #3 from kavehhn174/seeder

Seeder
This commit is contained in:
Kaveh HajiNajaf
2025-01-03 17:45:38 +03:30
committed by GitHub
14 changed files with 196 additions and 15 deletions
+2 -2
View File
@@ -12,7 +12,7 @@ const cors = require('cors')
const app = express()
const allowedOrigins = ['http://localhost:3000']
const allowedOrigins = ['http://localhost:3000', 'http://localhost:5173']
app.use(
cors({
@@ -32,7 +32,7 @@ app.use(express.json())
app.set('view engine', 'ejs')
app.use(express.static('views/public'))
app.use('/', routerEndpoints)
app.use('/api', routerEndpoints)
databaseConnection(app)
+7 -1
View File
@@ -26,11 +26,17 @@ const belongingSchema = new mongoose.Schema(
required: true,
},
},
documents: [String],
documentNames: [String],
documentUrls: [String],
imageNames: [String],
imageUrls: [String],
mainImageUrl: String,
mainImageName: String,
numId: {
type: Number,
unique: true,
},
tags: [String],
isActive: {
type: Boolean,
default: true,
+22
View File
@@ -0,0 +1,22 @@
const Category = require('./categoryModel')
const chalk = require('chalk')
const runSeeder = async () => {
const categories = [
{ nativeName: 'ساختمان', englishName: 'Building' },
{ nativeName: 'زمین', englishName: 'Lot' },
{ nativeName: 'کالا', englishName: 'Product' },
]
await Category.deleteMany({})
console.log(chalk.red('Deleted all category records.'))
await Category.create(categories, null)
console.log(
chalk.green.bold(
`CATEGORY: Created ${categories.length} category(ies)`
)
)
}
module.exports = { runSeeder }
+1 -1
View File
@@ -29,7 +29,7 @@ const runSeeder = async () => {
await Role.deleteMany({})
console.log(chalk.red('Deleted all role records.'))
await Role.insertMany(roles, null)
await Role.create(roles, null)
console.log(chalk.green.bold(`ROLE: Created ${roles.length} role(s)`))
}
+11
View File
@@ -1,6 +1,7 @@
// userController.js
const catchAsync = require('../../globalErrorHandler/catchAsync')
const userService = require('./userService')
const AppError = require("../../globalErrorHandler/AppError");
exports.signup = catchAsync(async (req, res, next) => {
const { user, token, cookieOptions } = await userService.signup(
@@ -55,6 +56,16 @@ exports.getAllUsers = catchAsync(async (req, res, next) => {
})
})
exports.userGetSelf = catchAsync(async (req, res, next) => {
const user = req.user
if (!user) {
throw new AppError('NotLoggedIn', 403, {})
}
return res.status(200).json({ status: 'success ', data: { user } })
})
exports.getUser = catchAsync(async (req, res, next) => {
const user = await userService.getUser(req.params.userId)
+4 -2
View File
@@ -5,13 +5,15 @@ const loginCheck = require('../../middlewares/loginCheck')
const router = new express.Router()
router.post('/signup', userController.signup)
router.post('/login', userController.loginUser)
router.post('/user/signup-email', userController.signup)
router.post('/user/login-email', userController.loginUser)
router.post('/logout', userController.logoutUser)
router.use(loginCheck.loginProtect)
// router.use(loginCheck.adminProtect)
router.get('/user/get-self', userController.userGetSelf)
router.get('/', userController.getAllUsers)
router.get('/:userId', userController.getUser)
+27
View File
@@ -0,0 +1,27 @@
const User = require('./userModel')
const chalk = require('chalk')
const runSeeder = async () => {
const users = [
{
_id: '66ddb52302f30f105de39e61',
name: 'main admin',
email: 'superadmin@belongingm.ir',
password: '$2a$10$pabxmRjm6klipAC6vBvgI.J.GJpnG//L1MeNcdbtxuYQRYHLI/I3O',
phoneNumber: '+989123456789',
favorites: [],
isVerified: false,
isCompleted: false,
shippingAddress: [],
bankAccount: [],
role: '66a2da5b9b989a8909948848',
},
]
await User.deleteMany({})
console.log(chalk.red('Deleted all user records.'))
await User.create(users, null)
console.log(chalk.green.bold(`USER: Created ${users.length} user(s)`))
}
module.exports = { runSeeder }
+2 -1
View File
@@ -3,7 +3,8 @@ NODE_ENV=development
PORT=3000
JWT_SECRET=Y@RJ$WT!@K0NS@MPL!
REDIS_URL= redis://:135792468@localhost:6379/0
LOGIN_ATTEMPT_LIMIT=5
LOGIN_ATTEMPT_LIMIT=900
SUPER_ADMIN_ROLE_ID=676afd6d076b286f9395b05f
TYPE_SENSE_URL=localhost:8108
TYPE_SENSE_API_KEY=vYQq7pTgl6ACoRy
SUPER_ADMIN_ID=66a2da5b9b989a8909948848
+3 -1
View File
@@ -7,7 +7,8 @@ exports.loginProtect = async (req, res, next) => {
// 1) Getting token and check if it's there
let token
token = req.cookies.jwt || req.cookies['crm-jwt']
token = req.cookies['bm-token']
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
token = req.headers.authorization.split(' ')[1]
@@ -30,6 +31,7 @@ exports.loginProtect = async (req, res, next) => {
// 3) check if user still exist
const loggedInUser = await User.findById(decodedToken.id).populate('role')
if (!loggedInUser) {
return next(new AppError('TokenUserNotExist', 401, {}))
}
+58 -5
View File
@@ -12,7 +12,7 @@
"axios": "^1.7.9",
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.3",
"chalk": "^5.3.0",
"chalk": "^4.1.2",
"compression": "^1.7.5",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
@@ -135,6 +135,20 @@
"node": ">= 0.6"
}
},
"node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/anymatch": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
@@ -290,16 +304,39 @@
}
},
"node_modules/chalk": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz",
"integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==",
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": "^12.17.0 || ^14.13 || >=16.0.0"
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/chalk/node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"engines": {
"node": ">=8"
}
},
"node_modules/chalk/node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
@@ -332,6 +369,22 @@
"node": ">=0.10.0"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+2 -1
View File
@@ -3,6 +3,7 @@
"version": "1.0.0",
"main": "app.js",
"scripts": {
"seed": "node ./seeder/seed.js",
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
@@ -14,7 +15,7 @@
"axios": "^1.7.9",
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.3",
"chalk": "^5.3.0",
"chalk": "^4.1.2",
"compression": "^1.7.5",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
+6
View File
@@ -0,0 +1,6 @@
require('dotenv').config({ path: './config/.env' })
const express = require('express')
const seederDBConnection = require('./seederDBConnection.js')
const app = express()
seederDBConnection(app)
+42
View File
@@ -0,0 +1,42 @@
const mongoose = require('mongoose')
const port = process.env.PORT || 3000
const env = process.env.NODE_ENV || 'development'
const redisClient = require('../setup/redis')
const seederRunner = require('./seederRunner')
const chalk = require('chalk')
module.exports = (app) => {
let connectionString
if (env === 'development') {
connectionString = process.env.MONGODB_URL
} else if (env === 'test') {
connectionString = process.env.MONGODB_URL
} else if (env === 'production') {
connectionString = process.env.MONGODB_URL
}
console.log(env)
mongoose
.connect(connectionString, {})
.then(function () {
console.log('MongoDB Database Connected')
redisClient.connect().then((r) => {
console.log('Redis connection Established')
app.listen(port, function () {
console.log('Server Started On Port ' + port)
console.log(
chalk.red.bold(
'-------- Running Seeders ---------'
)
)
seederRunner.run().then((r) => {
console.log(chalk.blue.bold('Seeding is done.'))
process.exit(0)
})
})
})
})
.catch(function (err) {
console.log(err)
})
}
+8
View File
@@ -0,0 +1,8 @@
const userSeeder = require('../components/user/userSeeder')
const categorySeeder = require('../components/category/categorySeeder')
const roleSeeder = require('../components/role/roleSeeder')
module.exports.run = async () => {
await userSeeder.runSeeder()
await categorySeeder.runSeeder()
await roleSeeder.runSeeder()
}