-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (82 loc) · 2.1 KB
/
index.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
'use strict'
const fp = require('fastify-plugin')
const qs = require('fast-querystring')
const pollRoute = require('./routes/main/post.js')
const getJobRoute = require('./routes/main/get.js')
const queueJobRoute = require('./routes/job/post.js')
const deleteJobRoute = require('./routes/main/delete.js')
const defaultOptions = {
getJob: async function () {
return null
},
getJobData: async function () {
return {}
},
queueJob: async function () {
return false
},
deleteJob: async function () {
return false
}
}
async function fastifyCloudPrnt (fastify, options = defaultOptions) {
const {
getJob,
getJobData,
queueJob,
deleteJob,
routePrefix,
templatesDir = '',
routeOptions = {},
defaultTemplate = 'receipt.stm',
formatPrntCommandData
} = {
...defaultOptions,
...options
}
const routes = [
pollRoute,
getJobRoute,
queueJobRoute,
deleteJobRoute
]
await fastify.decorate('cloudPrnt', {
getJob,
getJobData,
queueJob,
deleteJob,
templatesDir,
defaultTemplate,
formatPrntCommandData
})
fastify.register(async function (f) {
/**
* Some requests that are sent through the Star Micronics CloudPRNT protocol may include "application/x-www-form-urlencoded" data.
* As Fastify only natively supports 'application/json', we need to add an additional content-parser to handle requests with a
* "application/x-www-form-urlencoded" content-type.
*/
f.addContentTypeParser(
'application/x-www-form-urlencoded',
{ parseAs: 'buffer' },
function contentParser (req, body, done) {
f.log.debug(
`CloudPRNT request with "x-www-form-urlencoded" data received: ${req.method} ${req.url}\n` +
body.toString()
)
done(null, qs.parse(body.toString()))
}
)
routes.forEach(route => {
f.route({
...routeOptions,
...route
})
})
}, { prefix: routePrefix })
}
module.exports = fp(fastifyCloudPrnt, {
name: 'fastify-plugin',
decorators: ['view'],
dependencies: ['@fastify/view'],
fastify: '4.x'
})