This code creates a simple web server using the Express framework in Node.js, and it connects to a local SQLite database file named “bruh.db”. It first imports the necessary modules: Express for handling HTTP routes, CORS to allow cross-origin requests, and sqlite3 to interact with the database. The Express app is initialized, and middleware is added to enable CORS and to parse JSON request bodies. The server then starts listening on port 9000, and when it’s ready, it prints a confirmation message to the console.
The server defines several endpoints. The root endpoint (/) responds with a simple message indicating that the “Bruh database” is running. The /artists GET route queries all rows from the artists table in the database. If data is found, it sends it back in JSON format with a 200 status; if no data is found, it responds with a 404 and a “No Data!” message. If there is an error during the query, it returns the error in JSON format.
The POST route at /artists allows the client to insert a new artist into the database. It expects a JSON object in the request body containing a name field. If the insertion is successful, it returns a 201 status with a confirmation message; if there is an error, it sends the error back to the client.
Finally, the /genre-tracks GET route performs a join between the genres and tracks tables to retrieve a list of tracks along with their associated genre names. This data is returned as JSON. As with the other routes, if no data is found, it responds with a 404 and a “No Data!” message, and any query error is sent back in JSON format. This application provides basic read and write functionality for a music-related SQLite database using a RESTful API structure.
const cors = require('cors');
const app = express();
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database("./bruh.db");
app.use(cors());
app.use(express.json());
app.listen(9000, () => {
console.log("Nice");
});
app.get('/',(req,res)=>{
res.send("Bruh database")
});
app.get('/artists',(req,res)=>{
db.all("select * from artists",(error,rows)=>{
if(error){
res.json(error);
} else {
if(rows.length>0){
res.status(200).json(rows);
} else {
res.status(404).json({message:"No Data!"});
}
}
}
);
});
app.post('/artists',(req,res)=>{
const {name}=req.body;
db.run("insert into artists (name) values(?)",[name],error=>{
if(error) return res.send(error);
return res.status(201).json({message:"Data upload!"});
});
});
app.get('/genre-tracks',(req,res)=>{
db.all("select genres.Name as 'Genre name',tracks.Name as 'Tracks name' from genres,tracks where genres.GenreId = tracks.GenreId",(error,rows)=>{
if(error){
res.json(error);
} else {
if(rows.length>0){
res.status(200).json(rows);
} else {
res.status(404).json({message:"No Data!"});
}
}
}
);
});```


