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,11 +2,11 @@
<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>
<%~ E.includeFile("partials/foot.eta.html") %> <%~ E.includeFile("partials/foot.eta.html") %>

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,29 +1,25 @@
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!) prisma.item
if (req.originalUrl !== '/') { .findMany({
// TODO: Respond based on content-type (with req.is('application/json')) orderBy: {
res.status(404).render(__path + '/src/frontend/errors/404.eta.html', { url: req.originalUrl }); updatedAt: 'desc'
} else { },
prisma.item // Limit to 10 items
.findMany({ take: 10
orderBy: { })
updatedAt: 'desc' .then((items) => {
}, // Count amount of total items
// Limit to 10 items prisma.item.count().then((count) => {
take: 10 res.render(__path + '/src/frontend/dashboard.eta.html', { recents: items, stats: { total: count } });
})
.then((items) => {
// Count amount of total items
prisma.item.count().then((count) => {
res.render(__path + '/src/frontend/dashboard.eta.html', { recents: items, stats: { total: count } });
});
})
.catch((err) => {
console.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}); });
} })
}; .catch((err) => {
console.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,39 +1,39 @@
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 // Handle file upload and import
if (req.method === 'POST') { console.log(req.files);
// Handle file upload and import if (!req.files || Object.keys(req.files).length === 0) {
console.log(req.files) return res.status(400).send('No files were uploaded.');
if (!req.files || Object.keys(req.files).length === 0) { }
return res.status(400).send('No files were uploaded.');
}
const file: UploadedFile = req.files.formFile as UploadedFile; const file: UploadedFile = req.files.formFile as UploadedFile;
const csv = file.data.toString(); const csv = file.data.toString();
parse(csv, { columns: true }, function (err, records) { parse(csv, { columns: true }, function (err, records) {
if (err) { if (err) {
res.send(err); res.send(err);
return; return;
} }
// Find all categories and save them into a set // Find all categories and save them into a set
const categories = new Set<string>(); const categories = new Set<string>();
records.forEach((record: any) => { records.forEach((record: any) => {
categories.add(record.category); categories.add(record.category);
}); });
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,60 +44,61 @@ 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)
// Create items .then((values) => {
const listOfPromises = []; // Create items
const listOfPromises = [];
for (let i = 0; i < records.length; i++) { for (let i = 0; i < records.length; i++) {
const record = records[i]; const record = records[i];
const promise = prisma.item.create({ const promise = prisma.item.create({
data: { data: {
name: record.name, name: record.name,
amount: parseInt(record.amount), amount: parseInt(record.amount),
comment: record.comment, comment: record.comment,
category: { category: {
connect: { connect: {
name: record.category name: record.category
} }
}, },
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)
console.log(values); .then((values) => {
res.send('ok'); console.log(values);
}).catch((err) => { res.send('ok');
res.send('failed to create items'); })
.catch((err) => {
res.send('failed to create items');
log.db.error(err);
return;
});
})
.catch((err) => {
// res.send('failed to create categories');
log.db.error(err); log.db.error(err);
return;
}); });
}).catch((err) => { })
// res.send('failed to create categories'); .catch((err) => {
log.db.error(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) {
// Render page
res.render(__path + '/src/frontend/manage/imports/csvImport.eta.html');
}
export default { get, post };
} else {
// Render page
res.render(__path + '/src/frontend/manage/imports/csvImport.eta.html');
}
};

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);
export default Router; // 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;

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]);