-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
113 lines (88 loc) · 2.35 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
require('dotenv').config()
const fs = require('fs')
const path = require('path')
const neatCsv = require('neat-csv')
const express = require('express');
const multer = require('multer')
const app = express()
const db = require('./config/db')
// Configure static files
app.set('view engine', 'ejs')
app.set('views', 'views')
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.urlencoded({extended: false}))
// Form page (index)
app.get('/', async (req, res) => {
res.render('index',{
pageTitle: "Form"
})
})
// get all records from database
app.get('/record', (req, res) => {
db.searchByValue({
schema: process.env.SCHEMA,
table: "csv",
searchValue: "*",
searchAttribute: '_id',
attributes: ["*"]
}, (err, response) => {
if (err) return res.status(500).json({message: "Connection failed"})
console.log(response.data)
res.render('record',{
pageTitle: "csv",
records: response.data
})
})
})
// configure multer storage
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __dirname + '/public/assets/uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
// configure file filter
const fileFilter = function(req, file, cb) {
if(file.mimetype.split('/')[1] === 'csv'){
return cb(null, true)
}else{
return cb(new Error('Only csv files are allowed'), false)
}
}
// Calling multer function
const upload = multer({storage: storage, fileFilter: fileFilter})
// upload data to database
app.post('/upload', upload.single('file'), async (req, res) => {
try{
const data = await db.dropTable({
schema: process.env.SCHEMA,
table: 'csv'
})
}catch(e){
console.log('Failed to drop table')
}
try{
const data = await db.createTable({
schema: process.env.SCHEMA,
table: 'csv',
hashAttribute: '_id'
})
}catch(e){
console.log('Failed to create table')
}
fs.readFile(req.file.path, async (err, data) => {
const csvData = await neatCsv(data)
// insert file
db.insert({
schema: process.env.SCHEMA,
table: "csv",
records: csvData
}, (err, response) => {
if (err) return res.status(500).json(err)
res.redirect(302, "/record")
})
})
})
module.exports = app;