Fixed routing and publicInfoPage.

This commit is contained in:
Leon Meier 2023-05-15 01:37:51 +02:00
parent 1f2eb78333
commit ee61e94853
18 changed files with 170 additions and 160 deletions

View File

@ -2,10 +2,10 @@
<div class="text-center"> <div class="text-center">
<h2><%= it.name %></h2> <h2><%= it.name %></h2>
<p><strong>Category:</strong> <%= it.category%></p>
<p><strong>Amount:</strong> <%= it.Amount %></p>
<p><strong>SKU:</strong> <%= it.SKU %></p>
<p><strong>Comment:</strong> <%= it.comment %></p> <p><strong>Comment:</strong> <%= it.comment %></p>
<p><strong>Category:</strong> <%= it.category.name %></p>
<p><strong>Amount:</strong> <%= it.amount %></p>
<p><strong>SKU:</strong> <%= it.SKU %></p>
</div> </div>

View File

@ -44,7 +44,7 @@ export const prisma = new PrismaClient({
export const app = express(); export const app = express();
app.set('x-powered-by', false); app.set('x-powered-by', false);
app.set('strict routing', true); //app.set('strict routing', true);
app.engine('html', eta.renderFile); app.engine('html', eta.renderFile);
// app.use(cors()); // app.use(cors());
@ -58,10 +58,6 @@ app.use(fileUpload());
// app.use('/static', express.static('public')); // app.use('/static', express.static('public'));
app.use(express.static(__path + '/static')); app.use(express.static(__path + '/static'));
/* app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
}); */
//routes(app);
app.use(routes); app.use(routes);
app.listen(config.global.http_port, config.global.http_listen_address, () => { app.listen(config.global.http_port, config.global.http_listen_address, () => {

View File

@ -6,6 +6,7 @@ import testRoute from './test.js';
// Router base is '/api/v1' // Router base is '/api/v1'
const Router = express.Router({ strict: false }); const Router = express.Router({ strict: false });
Router.use('/test', testRoute); Router.route('/test').get(testRoute.get);
export default Router; export default Router;

View File

@ -1,5 +1,7 @@
import express, { Request, Response } from 'express'; import express, { Request, Response } from 'express';
export default (req: Request, res: Response) => { function get(req: Request, res: Response) {
res.status(200).send('API v1 Test Successful!'); res.status(200).send('API v1 Test Successful!');
}; };
export default { get };

View File

@ -1,11 +0,0 @@
import express from 'express';
// Route imports
// import setDemoData from './setDemoData.js';
// Router base is '/dev'
const Router = express.Router();
// Router.use("/setDemoData", setDemoData)
export default Router;

View File

@ -2,15 +2,28 @@ import { Request, Response } from 'express';
import { prisma, __path } from '../../index.js'; import { prisma, __path } from '../../index.js';
import * as Eta from 'eta'; import * as Eta from 'eta';
export default (req: Request, res: Response) => { function get(req: Request, res: Response) {
// retrieve data from database using id from url // Get data from database using sku from url.
prisma.item prisma.item
.findFirst({ .findFirst({
where: { where: {
SKU: req.params.id SKU: req.params.id
},
select: {
SKU: true,
name: true,
comment: true,
amount: true,
// Get category name from relation.
category: {
select: {
name: true
}
}
} }
}) })
.then((item) => { .then((item) => {
console.log(JSON.stringify(item));
if (item) { if (item) {
Eta.renderFile(__path + '/src/frontend/publicInfoPage.eta.html', item).then((html) => { Eta.renderFile(__path + '/src/frontend/publicInfoPage.eta.html', item).then((html) => {
res.send(html); res.send(html);
@ -19,4 +32,6 @@ export default (req: Request, res: Response) => {
res.send('Item not found'); res.send('Item not found');
} }
}); });
}; }
export default { get };

View File

@ -1,12 +1,7 @@
import express, { Request, Response } from 'express'; import express, { Request, Response } from 'express';
import { prisma, __path } from '../../index.js'; import { prisma, __path } from '../../index.js';
export default (req: Request, res: Response) => { function get(req: Request, res: Response) {
// TODO: Fix it? Express behaves like fucking shit with routers and /. Do not ask about it or touch it. EVER! (But if you can fix it a PR is welcome!)
if (req.originalUrl !== '/') {
// TODO: Respond based on content-type (with req.is('application/json'))
res.status(404).render(__path + '/src/frontend/errors/404.eta.html', { url: req.originalUrl });
} else {
prisma.item prisma.item
.findMany({ .findMany({
orderBy: { orderBy: {
@ -26,4 +21,5 @@ export default (req: Request, res: Response) => {
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err }); res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}); });
} }
};
export default { get };

View File

@ -5,15 +5,18 @@ import skuRoute from './:id.js';
import testRoute from './test.js'; import testRoute from './test.js';
import dashboardRoute from './dashboard.js'; import dashboardRoute from './dashboard.js';
import itemsRoute from './items.js'; import itemsRoute from './items.js';
import manage_routes from "./manage/index.js"; import manage_routes from './manage/index.js';
// Router base is '/' // Router base is '/'
const Router = express.Router({ strict: false }); const Router = express.Router({ strict: false });
Router.use('/test', testRoute); Router.route('/test').get(testRoute.get);
Router.use('/items', itemsRoute) Router.route('/items').get(itemsRoute.get);
Router.use('/:id(\\w{8})', skuRoute);
Router.route('/:id(\\w{8})').get(skuRoute.get);
Router.use('/manage', manage_routes); Router.use('/manage', manage_routes);
Router.use('/', dashboardRoute);
Router.route('/').get(dashboardRoute.get);
export default Router; export default Router;

View File

@ -1,7 +1,7 @@
import express, { Request, Response } from 'express'; import { Request, Response } from 'express';
import { prisma, __path } from '../../index.js'; import { prisma, __path } from '../../index.js';
export default (req: Request, res: Response) => { function get(req: Request, res: Response) {
prisma.item prisma.item
.findMany({}) .findMany({})
.then((items) => { .then((items) => {
@ -12,4 +12,6 @@ export default (req: Request, res: Response) => {
console.error(err); console.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err }); res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}); });
}; }
export default { get };

View File

@ -33,7 +33,7 @@ export default (req: Request, res: Response) => {
}, },
}) })
.then(() => { .then(() => {
res.redirect('/allCategories'); res.redirect('categories');
}) })
.catch((err) => { .catch((err) => {
// TODO Catch if is a duplicate error and show a message to the user // TODO Catch if is a duplicate error and show a message to the user
@ -52,7 +52,7 @@ export default (req: Request, res: Response) => {
}, },
}) })
.then(() => { .then(() => {
res.redirect('/allCategories'); res.redirect('categories');
}) })
.catch((err) => { .catch((err) => {
// TODO Catch if is a duplicate error and show a message to the user // TODO Catch if is a duplicate error and show a message to the user

View File

@ -1,14 +1,12 @@
import express, { Request, Response } from 'express'; import express, { Request, Response } from 'express';
import { prisma, __path, log } from '../../../../index.js'; import { prisma, __path, log } from '../../../../index.js';
import { UploadedFile } from 'express-fileupload'; import { UploadedFile } from 'express-fileupload';
import { parse, transform } from 'csv'; import { parse } from 'csv';
import { itemStatus, itemCategory, PrismaPromise } from '@prisma/client'; import { itemStatus, itemCategory, PrismaPromise } from '@prisma/client';
export default (req: Request, res: Response) => { function post(req: Request, res: Response) {
// Decide wether its post or get
if (req.method === 'POST') {
// Handle file upload and import // Handle file upload and import
console.log(req.files) console.log(req.files);
if (!req.files || Object.keys(req.files).length === 0) { if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.'); return res.status(400).send('No files were uploaded.');
} }
@ -27,13 +25,15 @@ export default (req: Request, res: Response) => {
}); });
log.db.debug(categories); log.db.debug(categories);
// Remove categories that already exists in the database // Remove categories that already exists in the database
prisma.itemCategory.findMany({ prisma.itemCategory
.findMany({
where: { where: {
name: { name: {
in: Array.from(categories) in: Array.from(categories)
} }
} }
}).then((values) => { })
.then((values) => {
values.forEach((value) => { values.forEach((value) => {
categories.delete(value.name); categories.delete(value.name);
}); });
@ -44,10 +44,11 @@ export default (req: Request, res: Response) => {
data: { data: {
name: category name: category
} }
}) });
categoryPromises.push(promise); categoryPromises.push(promise);
}); });
Promise.all(categoryPromises).then((values) => { Promise.all(categoryPromises)
.then((values) => {
// Create items // Create items
const listOfPromises = []; const listOfPromises = [];
@ -66,38 +67,38 @@ export default (req: Request, res: Response) => {
SKU: record.sku, SKU: record.sku,
manufacturer: record.manufacturer, manufacturer: record.manufacturer,
status: itemStatus.normal, status: itemStatus.normal,
importedBy: "CSV_IMPORT" importedBy: 'CSV_IMPORT'
} }
}); });
listOfPromises.push(promise); listOfPromises.push(promise);
} }
Promise.all(listOfPromises).then((values) => { Promise.all(listOfPromises)
.then((values) => {
console.log(values); console.log(values);
res.send('ok'); res.send('ok');
}).catch((err) => { })
.catch((err) => {
res.send('failed to create items'); res.send('failed to create items');
log.db.error(err); log.db.error(err);
return; return;
}); });
}).catch((err) => { })
.catch((err) => {
// res.send('failed to create categories'); // res.send('failed to create categories');
log.db.error(err); log.db.error(err);
}); });
})
.catch((err) => {
}).catch((err) => {
res.send('failed to find categories'); res.send('failed to find categories');
log.db.error(err); log.db.error(err);
return; return;
}); });
}); });
}
function get(req: Request, res: Response) {
} else {
// Render page // Render page
res.render(__path + '/src/frontend/manage/imports/csvImport.eta.html'); res.render(__path + '/src/frontend/manage/imports/csvImport.eta.html');
} }
}; export default { get, post };

View File

@ -10,11 +10,11 @@ import startpageRoute from './startpage.js';
// Router base is '/manage' // Router base is '/manage'
const Router = express.Router({ strict: false }); const Router = express.Router({ strict: false });
Router.route('/test').get(testRoute.get);
Router.use('/test', testRoute); Router.use('/categories', categoryManager); // TODO: Needs refactoring to new route format.
Router.use('/categories', categoryManager) Router.route('/storages').get(storageManager.get);
Router.use('/storages', storageManager) Router.route('/import/csv').get(csvImportRoute.get).post(csvImportRoute.post);
Router.use('/import/csv', csvImportRoute); Router.route('/').get(startpageRoute.get);
Router.use('/', startpageRoute);
export default Router; export default Router;

View File

@ -1,7 +1,8 @@
import express, { Request, Response } from 'express'; import express, { Request, Response } from 'express';
import { prisma, __path } from '../../../index.js'; import { prisma, __path } from '../../../index.js';
export default (req: Request, res: Response) => { function get(req: Request, res: Response) {
res.render(__path + '/src/frontend/manage/startpage.eta.html'); //, { items: items }); res.render(__path + '/src/frontend/manage/startpage.eta.html'); //, { items: items });
}
}; export default { get };

View File

@ -1,15 +1,8 @@
import express, { Request, Response } from 'express'; import express, { Request, Response } from 'express';
import { prisma, __path } from '../../../index.js'; import { prisma, __path } from '../../../index.js';
export default (req: Request, res: Response) => { function get(req: Request, res: Response) {
// prisma.item
// .findMany({})
// .then((items) => {
// Count amount of total items
res.render(__path + '/src/frontend/manage/storageManager.eta.html'); //, { items: items }); res.render(__path + '/src/frontend/manage/storageManager.eta.html'); //, { items: items });
// }) }
// .catch((err) => {
// console.error(err); export default { get };
// res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
// });
};

View File

@ -1,4 +1,7 @@
import express, { Request, Response } from 'express'; import { Request, Response } from 'express';
export default (req: Request, res: Response) => {
function get(req: Request, res: Response) {
res.status(200).send('Manage Test Successful!'); res.status(200).send('Manage Test Successful!');
}; }
export default { get };

View File

@ -1,4 +1,7 @@
import express, { Request, Response } from 'express'; import { Request, Response } from 'express';
export default (req: Request, res: Response) => {
res.status(200).send("Frontend Test Successful!"); function get(req: Request, res: Response) {
}; res.status(200).send('Frontend Test Successful!');
}
export default { get };

View File

@ -1,16 +1,21 @@
import express, { Express } from 'express'; import express, { Express } from 'express';
import { __path } from '../index.js';
// Route imports // Route imports
import frontend_routes from './frontend/index.js'; import frontend_routes from './frontend/index.js';
import static_routes from './static/index.js'; import static_routes from './static/index.js';
import api_routes from './api/index.js'; import api_routes from './api/index.js';
import dev_routes from './dev/index.js';
const Router = express.Router({ strict: false }); const Router = express.Router({ strict: false });
Router.use('/static', static_routes); Router.use('/static', static_routes);
Router.use('/api', api_routes); Router.use('/api', api_routes);
Router.use('/dev', dev_routes); // This is just for development. TODO: Add check if we are in devmode.
Router.use('/', frontend_routes); Router.use('/', frontend_routes);
// Default route.
Router.get('*', function (req, res) {
// TODO: Respond based on content-type (with req.is('application/json'))
res.status(404).render(__path + '/src/frontend/errors/404.eta.html', { url: req.originalUrl });
});
export default Router; export default Router;

View File

@ -11,7 +11,7 @@ const allowedURLs: Array<string> = JSON.parse(fs.readFileSync('allowedStaticPath
const recordedURLs: Array<string> = []; const recordedURLs: Array<string> = [];
const debugMode: boolean = JSON.parse(fs.readFileSync('allowedStaticPaths.json', 'utf8')).debugMode; const debugMode: boolean = JSON.parse(fs.readFileSync('allowedStaticPaths.json', 'utf8')).debugMode;
Router.use('*', (req: Request, res: Response) => { Router.get('*', (req: Request, res: Response) => {
if (debugMode) { if (debugMode) {
res.sendFile(Path.join(__path, 'node_modules', req.params[0])); res.sendFile(Path.join(__path, 'node_modules', req.params[0]));
recordedURLs.push(req.params[0]); recordedURLs.push(req.params[0]);