1
0
mirror of https://github.com/sasjs/server.git synced 2025-12-10 19:34:34 +00:00

fix: added db seed at server startup

This commit is contained in:
Saad Jutt
2022-04-19 23:25:05 +05:00
parent c7ffde1a3b
commit 2e63831b90
5 changed files with 42 additions and 3 deletions

View File

@@ -59,6 +59,6 @@ export default setProcessVariables().then(async () => {
app.use(onError)
await connectDB()
connectDB()
return app
})

View File

@@ -1,7 +1,8 @@
import mongoose from 'mongoose'
import { populateClients } from '../routes/api/auth'
import { seedDB } from './seedDB'
export const connectDB = async () => {
export const connectDB = () => {
// NOTE: when exporting app.js as agent for supertest
// we should exclude connecting to the real database
if (process.env.NODE_ENV === 'test') {
@@ -19,6 +20,8 @@ export const connectDB = async () => {
console.log('Connected to db!')
await seedDB()
await populateClients()
})
}

View File

@@ -9,7 +9,7 @@ export const sysInitCompiledPath = path.join(
)
export const sasJSCoreMacros = path.join(apiRoot, 'sasjscore')
export const sasJSCoreMacrosInfo = path.join(apiRoot, 'sasjscore', '.macrolist')
export const sasJSCoreMacrosInfo = path.join(sasJSCoreMacros, '.macrolist')
export const getWebBuildFolderPath = () =>
path.join(codebaseRoot, 'web', 'build')

View File

@@ -12,6 +12,7 @@ export * from './isDebugOn'
export * from './parseLogToArray'
export * from './removeTokensInDB'
export * from './saveTokensInDB'
export * from './seedDB'
export * from './setProcessVariables'
export * from './setupFolders'
export * from './upload'

35
api/src/utils/seedDB.ts Normal file
View File

@@ -0,0 +1,35 @@
import Client from '../model/Client'
import User from '../model/User'
const CLIENT = {
clientId: 'clientID1',
clientSecret: 'clientSecret'
}
const ADMIN_USER = {
id: 1,
displayName: 'Super Admin',
username: 'secretuser',
password: '$2a$10$hKvcVEZdhEQZCcxt6npazO6mY4jJkrzWvfQ5stdBZi8VTTwVMCVXO',
isAdmin: true,
isActive: true
}
export const seedDB = async () => {
// Checking if client is already in the database
const clientExist = await Client.findOne({ clientId: CLIENT.clientId })
if (!clientExist) {
const client = new Client(CLIENT)
await client.save()
console.log(`DB Seed - client created: ${CLIENT.clientId}`)
}
// Checking if user is already in the database
const usernameExist = await User.findOne({ username: ADMIN_USER.username })
if (!usernameExist) {
const user = new User(ADMIN_USER)
await user.save()
console.log(`DB Seed - admin account created: ${ADMIN_USER.username}`)
}
}