Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
foundation/exercises/03_databases/index.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
59 lines (50 sloc)
1.36 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
'use strict' | |
const express = require('express') | |
const app = express() | |
const port = 8080 | |
const sqlite3 = require('sqlite3').verbose() | |
const db = new sqlite3.Database('./bookshop.db', (err) => { | |
if (err) return console.error(err.message) | |
console.log('Connected to the "bookshop.db" SQlite database.') | |
}) | |
app.get('/', (req, res) => { | |
const sql = 'SELECT id, title FROM books;' | |
console.log(sql) | |
db.all(sql, (err, data) => { | |
if(err) console.error(err.message) | |
console.log(data) | |
for(const book of data) { | |
res.write(`${book.title}\n`) | |
} | |
res.end() | |
}) | |
}) | |
app.get('/books', (req, res) => { | |
const searchString = req.query.q | |
console.log(`searchString: ${searchString}`) | |
const sql = `SELECT id, title FROM books WHERE title LIKE "%${searchString}%";` | |
console.log(sql) | |
db.all(sql, (err, data) => { | |
if(err) console.error(err.message) | |
console.log(data) | |
for(const book of data) { | |
res.write(`${book.title}\n`) | |
} | |
res.end() | |
}) | |
}) | |
app.get('/details/:id', (req, res) => { | |
const bookID = req.params.id | |
console.log(bookID) | |
const sql = `SELECT * FROM books WHERE id = ${bookID};` | |
console.log(sql) | |
db.get(sql, (err, data) => { | |
if(err) console.error(err.message) | |
console.log(data) | |
res.write(`${data.title}\n\t`) | |
res.write(`${data.description}\n`) | |
res.end() | |
}) | |
}) | |
app.listen(port, () => console.log(`app listening on port ${port}`)) |