const express = require('express'); const router = express.Router(); const sql = require('mssql'); const { getUser } = require('../util.js'); router.get('/', async function(req, res, next) { // Get the product name to search for let name = req.query.productName; let content; let pool; let stmt; try { pool = await sql.connect(dbConfig); stmt = new sql.PreparedStatement(pool); stmt.input('name', sql.VarChar) await stmt.prepare(`select productId, productName, productPrice from product where productName like concat('%', @name, '%') `); const productResults = await stmt.execute({name:name}); content = `

All products ${name ? `matching ${name}` : ''}

${productResults.recordset.map(row => ` `).join('\n')}
Product Name Price
${row.productName} $${row.productPrice.toFixed(2)} Add to Cart
${ productResults.length === 0 ? `

Nothing to show!

` : '' } `; } catch (err) { content = err.toString(); console.error(err); } finally { if (stmt) stmt.unprepare(); if (pool) pool.close(); } res.render('layouts/main', { loggedIn: getUser(req) != null, user: getUser(req), spacer: true, content: `

Find what you're looking for

${content} `, }); }); module.exports = router;