|
|
@@ -0,0 +1,36 @@
|
|
|
+const jwt = require('jsonwebtoken');
|
|
|
+const { getMessages } = require('./databse.js')
|
|
|
+const authenticate = (req, res, next) => {
|
|
|
+ const token = req.headers.authorization?.split(' ')[1];
|
|
|
+ if (!token) return res.sendStatus(401);
|
|
|
+ jwt.verify(token, config.jwt.secret, (err, user) => {
|
|
|
+ if (err) return res.sendStatus(403);
|
|
|
+ req.user = user;
|
|
|
+ next();
|
|
|
+ });
|
|
|
+}
|
|
|
+
|
|
|
+export default async function (fastify) {
|
|
|
+ // 消息查询接口
|
|
|
+ fastify.get('/messages', authenticate, async () => {
|
|
|
+ return getMessages()
|
|
|
+ })
|
|
|
+
|
|
|
+ // 消息发布接口
|
|
|
+ fastify.post('/publish', authenticate, {
|
|
|
+ schema: {
|
|
|
+ body: {
|
|
|
+ type: 'object',
|
|
|
+ required: ['topic', 'message'],
|
|
|
+ properties: {
|
|
|
+ topic: { type: 'string' },
|
|
|
+ message: { type: 'string' }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }, async (request) => {
|
|
|
+ const { topic, message } = request.body
|
|
|
+ fastify.mqtt.publish(topic, message)
|
|
|
+ return { status: '消息已发布' }
|
|
|
+ })
|
|
|
+}
|