From 9292dc9fbd8e350012c0bcf7fd35651c98cc0944 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jakub=20=C5=A0indel=C3=A1=C5=99?=
Date: Tue, 17 Oct 2023 14:12:16 +0200
Subject: [PATCH] Migrate to ES6
---
app.js | 100 +++++++++++++---------------
bin/{www => www.js} | 12 ++--
defaults.env | 2 +-
functions/azure-passport.js | 35 +++++-----
functions/checkKiosk.js | 17 ++---
functions/database-backup.js | 21 +++---
functions/ensureAuthenticated.js | 13 ++--
functions/ensureAuthenticatedAPI.js | 31 ++++-----
functions/qrPayment.js | 50 +++++++-------
functions/sendMail.js | 76 ++++++++++-----------
models/delivery.js | 6 +-
models/invoice.js | 6 +-
models/order.js | 6 +-
models/product.js | 8 +--
models/user.js | 10 +--
package.json | 3 +-
routes/about.js | 8 +--
routes/add_products.js | 15 ++---
routes/admin/admin_dashboard.js | 11 ++-
routes/api/customerName.js | 11 ++-
routes/api/keypadOrder.js | 30 ++++-----
routes/auth_openid.js | 8 +--
routes/auth_openid_return.js | 8 +--
routes/auth_openid_return_post.js | 8 +--
routes/changelog.js | 8 +--
routes/index.js | 8 +--
routes/invoice.js | 29 ++++----
routes/invoices.js | 27 ++++----
routes/kiosk_keypad.js | 9 ++-
routes/kiosk_shop.js | 34 ++++------
routes/login.js | 8 +--
routes/logout.js | 6 +-
routes/new_product.js | 17 +++--
routes/orders.js | 15 ++---
routes/payments.js | 25 ++++---
routes/profile.js | 13 ++--
routes/shop.js | 34 ++++------
routes/stock.js | 13 ++--
seed/delivery-seeder.js | 16 ++---
seed/product-seeder.js | 8 +--
seed/user-seeder.js | 8 +--
tasks/daily-backup.js | 12 ++--
tasks/daily-report.js | 16 ++---
43 files changed, 381 insertions(+), 420 deletions(-)
rename bin/{www => www.js} (86%)
diff --git a/app.js b/app.js
index 0855684..74112c2 100755
--- a/app.js
+++ b/app.js
@@ -1,64 +1,60 @@
// Require all neccesary modules
-const createError = require('http-errors') // Generating errors
-const express = require('express') // Express
-const methodOverride = require('method-override')
-const path = require('path') // used for handling paths which held express files
-const cookieParser = require('cookie-parser')
-const expressSession = require('express-session')
-const handlebars = require('handlebars')
-const expressHbs = require('express-handlebars') // extended handlebars functionality
-const {
- allowInsecurePrototypeAccess
-} = require('@handlebars/allow-prototype-access')
-const mongoose = require('mongoose') // database
-const MongoStore = require('connect-mongo') // (expressSession)
-const passport = require('passport') // authentication method
-require('dotenv').config()
+import createError from 'http-errors' // Generating errors
+import express, { json, urlencoded } from 'express' // Express
+import methodOverride from 'method-override'
+import path, { join } from 'path' // used for handling paths which held express files
+import cookieParser from 'cookie-parser'
+import expressSession from 'express-session'
+import handlebars from 'handlebars'
+import { engine } from 'express-handlebars' // extended handlebars functionality
+import { allowInsecurePrototypeAccess } from '@handlebars/allow-prototype-access'
+import mongoose from 'mongoose' // database
+import connectMongo from 'connect-mongo' // (expressSession)
+import passport from 'passport' // authentication method
+import 'dotenv/config'
-let https
-let fs
-if (process.env.DEBUG.toLowerCase() === 'true') {
- https = require('https') // Using HTTPS for debug
- fs = require('fs') // Loading certificate from file for debug
-}
+import https from 'https' // Using HTTPS for debug
+import fs from 'fs' // Loading certificate from file for debug
+import { fileURLToPath } from 'url'
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
// Functions
-require('./functions/azure-passport')
+import './functions/azure-passport.js'
// Import scheduled tasks
-require('./tasks/daily-report')
-require('./tasks/daily-backup')
+import './tasks/daily-report.js'
+import './tasks/daily-backup.js'
// Load routes from routes folder to later app.use them.
// Access for all
-const indexRouter = require('./routes/index')
-const aboutRouter = require('./routes/about')
-const changelogRouter = require('./routes/changelog')
+import indexRouter from './routes/index.js'
+import aboutRouter from './routes/about.js'
+import changelogRouter from './routes/changelog.js'
// Access for logged in users
-const shopRouter = require('./routes/shop')
-const profileRouter = require('./routes/profile')
-const ordersRouter = require('./routes/orders')
-const invoicesRouter = require('./routes/invoices')
+import shopRouter from './routes/shop.js'
+import profileRouter from './routes/profile.js'
+import ordersRouter from './routes/orders.js'
+import invoicesRouter from './routes/invoices.js'
// Access for suppliers
-const addProductsRouter = require('./routes/add_products')
-const invoiceRouter = require('./routes/invoice')
-const paymentsRouter = require('./routes/payments')
-const stockRouter = require('./routes/stock')
-const newProductRouter = require('./routes/new_product')
+import addProductsRouter from './routes/add_products.js'
+import invoiceRouter from './routes/invoice.js'
+import paymentsRouter from './routes/payments.js'
+import stockRouter from './routes/stock.js'
+import newProductRouter from './routes/new_product.js'
// Access for admins
-const dashboardRouter = require('./routes/admin/admin_dashboard')
+import dashboardRouter from './routes/admin/admin_dashboard.js'
// Access for kiosk
-const kioskKeypadRouter = require('./routes/kiosk_keypad')
-const kioskShopRouter = require('./routes/kiosk_shop')
+import kioskKeypadRouter from './routes/kiosk_keypad.js'
+import kioskShopRouter from './routes/kiosk_shop.js'
// Passport routes
-const loginRouter = require('./routes/login')
-const logoutRouter = require('./routes/logout')
-const authOpenId = require('./routes/auth_openid')
-const authOpenIdReturnGet = require('./routes/auth_openid_return')
-const authOpenIdReturnPost = require('./routes/auth_openid_return_post')
+import loginRouter from './routes/login.js'
+import logoutRouter from './routes/logout.js'
+import authOpenId from './routes/auth_openid.js'
+import authOpenIdReturnGet from './routes/auth_openid_return.js'
+import authOpenIdReturnPost from './routes/auth_openid_return_post.js'
// API routes
-const keypadOrderRouter = require('./routes/api/keypadOrder')
-const customerName = require('./routes/api/customerName')
+import keypadOrderRouter from './routes/api/keypadOrder.js'
+import customerName from './routes/api/customerName.js'
// Express app and database connection
const app = express()
@@ -67,7 +63,7 @@ mongoose.connect(process.env.DB_CONNECTION_STRING)
// View engine setup
app.engine(
'.hbs',
- expressHbs.engine({
+ engine({
defaultLayout: 'layout',
extname: '.hbs',
handlebars: allowInsecurePrototypeAccess(handlebars)
@@ -77,10 +73,10 @@ app.enable('trust proxy')
app.set('view engine', '.hbs')
app.enable('view cache')
app.use(methodOverride())
-app.use(express.json())
-app.use(express.static(path.join(__dirname, 'public')))
+app.use(json())
+app.use(express.static(join(__dirname, 'public')))
app.use(
- express.urlencoded({
+ urlencoded({
extended: true
})
)
@@ -96,7 +92,7 @@ app.use(
sameSite: 'None',
resave: false,
saveUninitialized: false,
- store: MongoStore.create({
+ store: connectMongo.create({
mongoUrl: process.env.DB_CONNECTION_STRING,
mongooseConnection: mongoose.connection,
ttl: 14 * 24 * 60 * 60,
@@ -167,4 +163,4 @@ if (process.env.DEBUG.toLowerCase() === 'true') {
https.createServer(options, app).listen(process.env.APP_PORT_SSL || 443)
}
-module.exports = app
+export default app
diff --git a/bin/www b/bin/www.js
similarity index 86%
rename from bin/www
rename to bin/www.js
index 7485e27..aa57865 100644
--- a/bin/www
+++ b/bin/www.js
@@ -4,9 +4,11 @@
* Module dependencies.
*/
-var app = require('../app')
-var debug = require('debug')('small-bussiness-fridge:server')
-var http = require('http')
+import app from '../app.js'
+import debug from 'debug'
+import { createServer } from 'http'
+
+const logger = debug('small-bussiness-fridge:server')
/**
* Get port from environment and store in Express.
@@ -19,7 +21,7 @@ app.set('port', port)
* Create HTTP server.
*/
-var server = http.createServer(app)
+var server = createServer(app)
/**
* Listen on provided port, on all network interfaces.
@@ -80,5 +82,5 @@ function onError(error) {
function onListening() {
var addr = server.address()
var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port
- debug('Listening on ' + bind)
+ logger('Listening on ' + bind)
}
diff --git a/defaults.env b/defaults.env
index 7afd88a..81ced0c 100644
--- a/defaults.env
+++ b/defaults.env
@@ -7,7 +7,7 @@ API_SECRET=veryveryverysecretapikey
DEBUG=false
MAIL_PORT=25
MAIL_HOST=localhost
-MAIL_FROM='Lednice IT'
+MAIL_FROM=Lednice IT
MAIL_USERNAME=noreply@example.com
MAIL_PASSWORD=somerandompassword
MAIL_SYSTEM=helpdesk@example.com
diff --git a/functions/azure-passport.js b/functions/azure-passport.js
index 61fb7a8..edd9ee7 100644
--- a/functions/azure-passport.js
+++ b/functions/azure-passport.js
@@ -1,7 +1,7 @@
// modules and functions require
-const mailer = require('./sendMail')
-const passport = require('passport')
-const OIDCStrategy = require('passport-azure-ad').OIDCStrategy
+import { sendMail } from './sendMail.js'
+import passport from 'passport'
+import { OIDCStrategy } from 'passport-azure-ad'
const cookieEncryptionKeys = [
{
@@ -11,13 +11,15 @@ const cookieEncryptionKeys = [
]
// Mongoose Data object
-const User = require('../models/user')
+// import module as User from '../Users/user.js'
+import model from '../models/user.js'
// Helper function to find user in database
const findByOid = function (oid, fn) {
- User.findOne({
- oid
- })
+ model
+ .findOne({
+ oid
+ })
.then((user) => {
return fn(null, user)
})
@@ -48,8 +50,7 @@ passport.use(
responseMode: process.env.CREDS_RESPONSE_MODE,
redirectUrl: process.env.CREDS_REDIRECT_URL,
allowHttpForRedirectUrl:
- process.env.CREDS_ALLOW_HTTP_FOR_REDIRECT_URL.toLowerCase() ===
- 'true' || false,
+ process.env.CREDS_ALLOW_HTTP_FOR_REDIRECT_URL === 'true' || false,
clientSecret: process.env.CREDS_CLIENT_SECRET,
validateIssuer:
process.env.CREDS_VALIDATE_ISSUER.toLowerCase() === 'true' || false,
@@ -81,9 +82,10 @@ passport.use(
}
if (!user) {
// Auto-registration
- User.findOne({
- oid: profile.oid
- })
+ user
+ .findOne({
+ oid: profile.oid
+ })
.then((user) => {
// If user does not exist in database, automatically register as customer (not admin, not supplier, auto increment keypad ID)
if (!user) {
@@ -99,7 +101,8 @@ passport.use(
profile.supplier = false
// Async function to find highest keypad ID and increment it by one.
const latestUser = function (callback) {
- User.find()
+ model
+ .find()
.sort({
keypadId: -1
})
@@ -125,9 +128,9 @@ passport.use(
.save()
.then((res) => {
// console.log(`New User ${newUser.displayName} inserted into database.`);
- const subject = `Welcome to our fridge ${newUser.displayName}`
- const body = `
Welcome abord!
Hope you will like it here
Your keypad ID is: ${newUser.keypadID}
`
- mailer.sendMail(newUser.email, subject, body)
+ const subject = `Lednice IT je pyšná, že ji navštívila osoba jménem ${newUser.displayName}`
+ const body = `
Lednice IT Vás vítá!
Snad se Vám zde bude líbit.
Vaše ID pro objednávání skrze kiosek: ${newUser.keypadID}
Jak to funguje
Do Lednice IT dodává produkty více dodavatelů. Zákazník si přes e-shop či přes kiosek zakoupí vybraný produkt. Až se dodavateli nashromáždí dostatek prodaného zboží, vytvoří hromadnou fakturaci. Každý zákazník, který si u daného dodavatele něco zakoupil obdrží e-mail s QR kódem, který uhradí. Platbu obě strany potvrdí v rozhraní e-shopu.
Pokud se budete chtít stát dodavatelem, kontaktujte správce Lednice IT.
`
+ sendMail(newUser.email, subject, body)
})
.catch((err) => {
console.log(err)
diff --git a/functions/checkKiosk.js b/functions/checkKiosk.js
index 76b844f..09e31ae 100644
--- a/functions/checkKiosk.js
+++ b/functions/checkKiosk.js
@@ -1,12 +1,9 @@
-module.exports = {
- // Checks if user is not a kiosk user, if kiosk, redirect to kiosk page.
- checkKiosk: function (req, res, next) {
- if (!req.user) {
- return next()
- }
- if (!req.user.kiosk) {
- return next()
- }
- res.redirect('/kiosk_keypad')
+export function checkKiosk(req, res, next) {
+ if (!req.user) {
+ return next()
}
+ if (!req.user.kiosk) {
+ return next()
+ }
+ res.redirect('/kiosk_keypad')
}
diff --git a/functions/database-backup.js b/functions/database-backup.js
index e5d0d47..440573d 100644
--- a/functions/database-backup.js
+++ b/functions/database-backup.js
@@ -1,7 +1,10 @@
-const fs = require('fs')
-const _ = require('lodash')
-const exec = require('child_process').exec
-const path = require('path')
+import fs from 'fs'
+import _ from 'lodash'
+import { exec } from 'child_process'
+import path from 'path'
+import { fileURLToPath } from 'url'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
// Concatenate root directory path with our backup folder.
const backupDirPath = path.join(__dirname, '../database-backup/backup')
@@ -14,12 +17,12 @@ const dbOptions = {
}
// return stringDate as a date object.
-exports.stringToDate = (dateString) => {
+function stringToDate(dateString) {
return new Date(dateString)
}
// Check if variable is empty or not.
-exports.empty = (mixedVar) => {
+function empty(mixedVar) {
let undef, key, i, len
const emptyValues = [undef, null, false, 0, '', '0']
for (i = 0, len = emptyValues.length; i < len; i++) {
@@ -37,7 +40,7 @@ exports.empty = (mixedVar) => {
}
// Auto backup function
-exports.dbAutoBackUp = () => {
+export default function dbAutoBackUp() {
// check for auto backup is enabled or disabled
if (dbOptions.autoBackup === true) {
console.log(backupDirPath)
@@ -45,7 +48,7 @@ exports.dbAutoBackUp = () => {
let beforeDate, oldBackupDir, oldBackupPath
// Current date
- var currentDate = this.stringToDate(date)
+ var currentDate = stringToDate(date)
const newBackupDir =
currentDate.getFullYear() +
'-' +
@@ -80,7 +83,7 @@ exports.dbAutoBackUp = () => {
newBackupPath
exec(cmd, (error, stdout, stderr) => {
- if (this.empty(error)) {
+ if (empty(error)) {
// check for remove old backup after keeping # of days given in ENV.
if (dbOptions.removeOldBackup === true) {
if (fs.existsSync(oldBackupPath)) {
diff --git a/functions/ensureAuthenticated.js b/functions/ensureAuthenticated.js
index 9274dda..fc1d737 100644
--- a/functions/ensureAuthenticated.js
+++ b/functions/ensureAuthenticated.js
@@ -1,10 +1,7 @@
-module.exports = {
- // Uses passport functionality, which checks if user is logged in. If not, redirects to login page.
- ensureAuthenticated: function (req, res, next) {
- if (req.isAuthenticated()) {
- return next()
- }
- console.log('redirecting')
- res.redirect('/login')
+export function ensureAuthenticated(req, res, next) {
+ if (req.isAuthenticated()) {
+ return next()
}
+ console.log('redirecting')
+ res.redirect('/login')
}
diff --git a/functions/ensureAuthenticatedAPI.js b/functions/ensureAuthenticatedAPI.js
index cc996f1..05b327c 100644
--- a/functions/ensureAuthenticatedAPI.js
+++ b/functions/ensureAuthenticatedAPI.js
@@ -1,22 +1,19 @@
var responseJson
-module.exports = {
- // Checks if request contains expected API secret. If it does, proceed without problem, otherwise respond with error JSON.
- ensureAuthenticatedAPI: function (req, res, next) {
- // Check if request header contains API secret key
- if (req.get('sbf-API-secret') !== process.env.API_SECRET) {
- res.status(401)
- res.set('Content-Type', 'application/problem+json')
- responseJson = {
- type: 'https://github.com/houby-studio/small-business-fridge/wiki/API-documentation#api-protection',
- title: 'Your request does not contain secret key.',
- status: 401,
- 'detail:':
- 'This is not a public function. To use this API, you need to supply secret key in the header. More details can be found in documentation https://git.io/Jeodr'
- }
- res.json(responseJson)
- return
+export function ensureAuthenticatedAPI(req, res, next) {
+ // Check if request header contains API secret key
+ if (req.get('sbf-API-secret') !== process.env.API_SECRET) {
+ res.status(401)
+ res.set('Content-Type', 'application/problem+json')
+ responseJson = {
+ type: 'https://github.com/houby-studio/small-business-fridge/wiki/API-documentation#api-protection',
+ title: 'Your request does not contain secret key.',
+ status: 401,
+ 'detail:':
+ 'This is not a public function. To use this API, you need to supply secret key in the header. More details can be found in documentation https://git.io/Jeodr'
}
- return next()
+ res.json(responseJson)
+ return
}
+ return next()
}
diff --git a/functions/qrPayment.js b/functions/qrPayment.js
index 3235643..b0e37b9 100644
--- a/functions/qrPayment.js
+++ b/functions/qrPayment.js
@@ -1,31 +1,27 @@
-var qrcode = require('qrcode')
+import { toDataURL } from 'qrcode'
-module.exports = {
- // Generates QRCode for mobile payment. Generated amount is in CZK. For more details refer to QRCode payment standard.
- // Example: generateQR('CZ0123456789012345678900', 500, )
- generateQR: function (IBAN, amount, payer, receiver, callback) {
- if (!IBAN) {
- return callback()
- } else if (!amount) {
- return callback()
- } else if (!payer) {
- return callback()
- }
- var msgTemplate = 'LEDNICE IT - '
- // MSG max length is 60 characters
- if (payer.length + msgTemplate.length > 60) {
- payer.substring(0, 60)
- }
+export function generateQR(IBAN, amount, payer, receiver, callback) {
+ if (!IBAN) {
+ return callback()
+ } else if (!amount) {
+ return callback()
+ } else if (!payer) {
+ return callback()
+ }
+ var msgTemplate = 'LEDNICE IT - '
+ // MSG max length is 60 characters
+ if (payer.length + msgTemplate.length > 60) {
+ payer.substring(0, 60)
+ }
- // Put together QRCode payment string, remove special characters and convert to uppercase to make QRCode ALPHANUMERIC only to reduce size
- var code = `SPD*1.0*ACC:${IBAN}*AM:${amount}*CC:CZK*RN:${receiver}*MSG:${msgTemplate}${payer}`
- code = code
- .normalize('NFD')
- .replace(/[\u0300-\u036f]/g, '')
- .toUpperCase()
+ // Put together QRCode payment string, remove special characters and convert to uppercase to make QRCode ALPHANUMERIC only to reduce size
+ var code = `SPD*1.0*ACC:${IBAN}*AM:${amount}*CC:CZK*RN:${receiver}*MSG:${msgTemplate}${payer}`
+ code = code
+ .normalize('NFD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .toUpperCase()
- qrcode.toDataURL(code, function (_err, url) {
- return callback(url)
- })
- }
+ toDataURL(code, function (_err, url) {
+ return callback(url)
+ })
}
diff --git a/functions/sendMail.js b/functions/sendMail.js
index d80bbc9..f64460d 100644
--- a/functions/sendMail.js
+++ b/functions/sendMail.js
@@ -1,47 +1,43 @@
-var nodemailer = require('nodemailer')
+import { createTransport } from 'nodemailer'
-module.exports = {
- // Sends e-mail. Most parameters taken from ENV. Function takes recipient, subject, body and optional one image.
- // Example: sendMail('james.jameson@example.com', 'Hello there', '
Some lengthy message
', './images/logo.png')
- sendMail: function (mailto, mailsubject, mailbody, image) {
- // In case system error occurs, send warning to mail obtained from config.
- if (mailto === 'system') {
- mailto = process.env.MAIL_SYSTEM
- }
-
- var transporter = nodemailer.createTransport({
- port: process.env.MAIL_PORT,
- host: process.env.MAIL_HOST,
- auth: {
- user: process.env.MAIL_USERNAME,
- pass: process.env.MAIL_PASSWORD
- },
- tls: {
- rejectUnauthorized: false
- }
- })
+export function sendMail(mailto, mailsubject, mailbody, image) {
+ // In case mail is destined for system administrator or we run in development environment, send all e-mails to system address obtained from config.
+ if (process.env.NODE_ENV === 'development' || mailto === 'system@system') {
+ mailto = process.env.MAIL_SYSTEM
+ }
- var mailOptions = {
- from: {
- name: process.env.MAIL_FROM,
- address: process.env.MAIL_USERNAME
- },
- to: mailto,
- subject: mailsubject,
- html: mailbody
+ var transporter = createTransport({
+ port: process.env.MAIL_PORT,
+ host: process.env.MAIL_HOST,
+ auth: {
+ user: process.env.MAIL_USERNAME,
+ pass: process.env.MAIL_PASSWORD
+ },
+ tls: {
+ rejectUnauthorized: false
}
+ })
- if (image) {
- mailOptions.attachments = [
- {
- path: `./public/${image}`,
- cid: 'image@prdelka.eu'
- }
- ]
- }
+ var mailOptions = {
+ from: {
+ name: process.env.MAIL_FROM,
+ address: process.env.MAIL_USERNAME
+ },
+ to: mailto,
+ subject: mailsubject,
+ html: mailbody
+ }
- transporter.sendMail(mailOptions, function (error, info) {
- if (error) console.log(error)
- })
+ if (image) {
+ mailOptions.attachments = [
+ {
+ path: `./public/${image}`,
+ cid: 'image@prdelka.eu'
+ }
+ ]
}
+
+ transporter.sendMail(mailOptions, function (error, info) {
+ if (error) console.log(error)
+ })
}
diff --git a/models/delivery.js b/models/delivery.js
index ad984a6..be14860 100644
--- a/models/delivery.js
+++ b/models/delivery.js
@@ -1,5 +1,5 @@
-var mongoose = require('mongoose')
-var Schema = mongoose.Schema
+import { Schema as _Schema, model } from 'mongoose'
+var Schema = _Schema
var schema = new Schema({
supplierId: {
@@ -33,4 +33,4 @@ var schema = new Schema({
}
})
-module.exports = mongoose.model('Delivery', schema)
+export default model('Delivery', schema)
diff --git a/models/invoice.js b/models/invoice.js
index 4610a67..3e78f70 100644
--- a/models/invoice.js
+++ b/models/invoice.js
@@ -1,5 +1,5 @@
-var mongoose = require('mongoose')
-var Schema = mongoose.Schema
+import { Schema as _Schema, model } from 'mongoose'
+var Schema = _Schema
var schema = new Schema({
buyerId: {
@@ -36,4 +36,4 @@ var schema = new Schema({
}
})
-module.exports = mongoose.model('Invoice', schema)
+export default model('Invoice', schema)
diff --git a/models/order.js b/models/order.js
index 522398d..ad66987 100644
--- a/models/order.js
+++ b/models/order.js
@@ -1,5 +1,5 @@
-var mongoose = require('mongoose')
-var Schema = mongoose.Schema
+import { Schema as _Schema, model } from 'mongoose'
+var Schema = _Schema
var schema = new Schema({
buyerId: {
@@ -31,4 +31,4 @@ var schema = new Schema({
}
})
-module.exports = mongoose.model('Order', schema)
+export default model('Order', schema)
diff --git a/models/product.js b/models/product.js
index 5e797eb..d9728f0 100644
--- a/models/product.js
+++ b/models/product.js
@@ -1,6 +1,6 @@
-var mongoose = require('mongoose')
-var Schema = mongoose.Schema
-var uniqueValidator = require('mongoose-unique-validator')
+import { Schema as _Schema, model } from 'mongoose'
+var Schema = _Schema
+import uniqueValidator from 'mongoose-unique-validator'
var schema = new Schema({
keypadId: {
@@ -25,4 +25,4 @@ var schema = new Schema({
schema.plugin(uniqueValidator)
-module.exports = mongoose.model('Product', schema)
+export default model('Product', schema)
diff --git a/models/user.js b/models/user.js
index 644b4a1..40a0c33 100755
--- a/models/user.js
+++ b/models/user.js
@@ -1,7 +1,6 @@
-var mongoose = require('mongoose')
-var Schema = mongoose.Schema
+import mongoose, { Schema } from 'mongoose'
-var schema = new Schema({
+const userSchema = new Schema({
oid: {
type: String,
required: true
@@ -49,4 +48,7 @@ var schema = new Schema({
}
})
-module.exports = mongoose.model('User', schema)
+const model = mongoose.model('User', userSchema)
+
+export const schema = model.schema
+export default model
diff --git a/package.json b/package.json
index e659f75..74bcc5c 100644
--- a/package.json
+++ b/package.json
@@ -2,8 +2,9 @@
"name": "small-bussiness-fridge",
"version": "1.0.4",
"private": true,
+ "type": "module",
"scripts": {
- "start": "node ./bin/www",
+ "start": "node ./bin/www.js",
"lint": "eslint .",
"make-env": "cp ./config/example.config.js ./config/config.js && bash ./test/setup_env.sh",
"test": "mocha test --check-leaks --exit --timeout 5000 --globals __coverage__",
diff --git a/routes/about.js b/routes/about.js
index aec8435..89fb264 100644
--- a/routes/about.js
+++ b/routes/about.js
@@ -1,6 +1,6 @@
-var express = require('express')
-var router = express.Router()
-var checkKiosk = require('../functions/checkKiosk').checkKiosk
+import { Router } from 'express'
+var router = Router()
+import { checkKiosk } from '../functions/checkKiosk.js'
/* GET about page. */
router.get('/', checkKiosk, function (req, res, next) {
@@ -10,4 +10,4 @@ router.get('/', checkKiosk, function (req, res, next) {
})
})
-module.exports = router
+export default router
diff --git a/routes/add_products.js b/routes/add_products.js
index bda4d81..e002992 100644
--- a/routes/add_products.js
+++ b/routes/add_products.js
@@ -1,10 +1,9 @@
-var express = require('express')
-var router = express.Router()
-var ensureAuthenticated =
- require('../functions/ensureAuthenticated').ensureAuthenticated
-var Product = require('../models/product')
-var Delivery = require('../models/delivery')
-var csrf = require('csurf')
+import { Router } from 'express'
+var router = Router()
+import { ensureAuthenticated } from '../functions/ensureAuthenticated.js'
+import Product from '../models/product.js'
+import Delivery from '../models/delivery.js'
+import csrf from 'csurf'
var csrfProtection = csrf()
router.use(csrfProtection)
@@ -95,4 +94,4 @@ router.post('/', ensureAuthenticated, function (req, res) {
})
})
-module.exports = router
+export default router
diff --git a/routes/admin/admin_dashboard.js b/routes/admin/admin_dashboard.js
index 9151cad..f3eb225 100644
--- a/routes/admin/admin_dashboard.js
+++ b/routes/admin/admin_dashboard.js
@@ -1,8 +1,7 @@
-var express = require('express')
-var router = express.Router()
-var ensureAuthenticated =
- require('../../functions/ensureAuthenticated').ensureAuthenticated
-var csrf = require('csurf')
+import { Router } from 'express'
+var router = Router()
+import { ensureAuthenticated } from '../../functions/ensureAuthenticated.js'
+import csrf from 'csurf'
var csrfProtection = csrf()
router.use(csrfProtection)
@@ -24,4 +23,4 @@ router.get('/', ensureAuthenticated, function (req, res) {
})
})
-module.exports = router
+export default router
diff --git a/routes/api/customerName.js b/routes/api/customerName.js
index 397f5ba..ca61465 100644
--- a/routes/api/customerName.js
+++ b/routes/api/customerName.js
@@ -1,8 +1,7 @@
-const express = require('express')
-const router = express.Router()
-const ensureAuthenticatedAPI =
- require('../../functions/ensureAuthenticatedAPI').ensureAuthenticatedAPI
-const User = require('../../models/user')
+import { Router } from 'express'
+const router = Router()
+import { ensureAuthenticatedAPI } from '../../functions/ensureAuthenticatedAPI.js'
+import User from '../../models/user.js'
let responseJson
// GET /api/customerName - accepts customer's keypadId and returns customer's display name
@@ -67,4 +66,4 @@ router.get('/', ensureAuthenticatedAPI, function (req, res, next) {
})
})
-module.exports = router
+export default router
diff --git a/routes/api/keypadOrder.js b/routes/api/keypadOrder.js
index 1b1b7ea..7e57830 100644
--- a/routes/api/keypadOrder.js
+++ b/routes/api/keypadOrder.js
@@ -1,13 +1,12 @@
-const express = require('express')
-const router = express.Router()
-const moment = require('moment')
-const mailer = require('../../functions/sendMail')
-const User = require('../../models/user')
-const Order = require('../../models/order')
-const Product = require('../../models/product')
-const Delivery = require('../../models/delivery')
-const ensureAuthenticatedAPI =
- require('../../functions/ensureAuthenticatedAPI').ensureAuthenticatedAPI
+import { Router } from 'express'
+const router = Router()
+import moment from 'moment'
+import { sendMail } from '../../functions/sendMail.js'
+import User from '../../models/user.js'
+import Order from '../../models/order.js'
+import Product from '../../models/product.js'
+import Delivery from '../../models/delivery.js'
+import { ensureAuthenticatedAPI } from '../../functions/ensureAuthenticatedAPI.js'
let responseJson
/* API to order via keypad */
@@ -139,12 +138,7 @@ router.post('/', ensureAuthenticatedAPI, function (req, res, next) {
} Cena: ${
product[0].stock[0].price
}Kč Kdy: ${moment().format('LLLL')}