I am currently stuck on trying to run multiple insert SQL statements on my app.post function in server.js. This is for a Video Game database. First, I was trying the method that is commented out but would receive an error saying "column index out of range" when trying to insert a new game. So then I tried the uncommented functions to see if I could do one at a time instead, but the error I receive now is "cannot set headers after they are sent to the client"
//Server.js
// videogames.insertNewGame(data.gameTitle, data.year, data.genre, data.publisher, data.developer, data.platformCB)
// .then(insertNew => {
// res.json({
// "message":`Success! New Game Added`,
// "data":insertNew
// })
// })
// .catch(err => {
// res.status(400).json({"error":err.message})
// })
videogames.insertNewGame(data.gameTitle, data.year, data.genre)
.then(insertNew => {
res.json({
"message":`Success! New Game Added`,
"data":insertNew
})
})
.catch(err => {
res.status(400).json({"error":err.message})
})
videogames.updateNewGame(data.gameTitle, data.platformCB)
.then(insertNew => {
res.json({
"message":`Success! Updated exKey`,
"data":insertNew
})
})
.catch(err => {
res.status(400).json({"error":err.message})
})
//database.js
// insertNewGame(gTitle, gYear, gGenre, pPub, dDev, pfCB){
// return this.all(
// "INSERT INTO Games (g_title, g_year, g_genre) VALUES(?, ?, ?); " +
// "UPDATE Games SET g_exkey = (SELECT pf_exkey FROM Platform WHERE pf_system = ?) WHERE g_title = ?; " +
// "INSERT INTO Publisher (p_name) VALUES(?); " +
// "INSERT INTO Developer (d_name) VALUES(?); " +
// "INSERT INTO Contracts (c_gameID, c_pubkey, c_devkey) " +
// "SELECT g_gameID, p_pubkey, d_devkey " +
// "FROM Games, Publisher, Developer " +
// "WHERE g_title = ? AND " +
// "p_name = ? AND " +
// "d_name = ?", [gTitle, gYear, gGenre, pfCB, gTitle, pPub, dDev, gTitle, pPub, dDev])
// }
insertNewGame(gTitle, gYear, gGenre){
return this.all(
"INSERT INTO Games (g_title, g_year, g_genre) VALUES(?, ?, ?)", [gTitle, gYear, gGenre]
)
}
updateNewGame(gTitle, pCB){
return this.all(
"UPDATE Games SET g_exkey = (SELECT pf_exkey FROM Platform WHERE pf_system = ?) WHERE g_title = ?", [gTitle, pCB]
)
}
insertPublisher(pPub){
"this.all" calls this function
//database.js
class DB{
constructor(){
this.db = new sqlite3.Database(DBSOURCE, (err) => {
if(err){ //callback
// Cannot open Database
console.error(err.message)
throw err
}else{
console.log('Connnected to the SQLite database.')
}
})
}
all(sql, params = []) {
return new Promise((resolve, reject) => {
this.db.all(sql, params, (err, rows) => {
if(err){
console.log('Error running sql: ' + sql)
console.log(err)
reject(err)
} else{
resolve(rows)
}
})
})
}
...
}
Just to clarify, I get all of my data from my HTML form data section and then set it to what you see here, "data.publisher, data.developer, ..."