OcrDevicesController.ts 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
  2. import PaginationService from 'App/Services/PaginationService'
  3. import { schema } from '@ioc:Adonis/Core/Validator'
  4. import OcrDevice from 'App/Models/OcrDevice'
  5. import OcrChannel from 'App/Models/OcrChannel'
  6. export default class OcrDevicesController {
  7. private paginationService = new PaginationService(OcrDevice)
  8. public async index({ request }: HttpContextContract) {
  9. return await this.paginationService.paginate(request.all())
  10. }
  11. public async store({ request, bouncer }: HttpContextContract) {
  12. // await bouncer.authorize('admin')
  13. const data = await request.validate({
  14. schema: schema.create({
  15. id: schema.string(),
  16. platform: schema.string(),
  17. channel: schema.string(),
  18. deviceInfo: schema.string.optional(),
  19. total: schema.number(),
  20. scanned: schema.number(),
  21. ipAddress: schema.string.optional()
  22. })
  23. })
  24. const clientIp = request.ip()
  25. if (!data.ipAddress) {
  26. data.ipAddress = clientIp
  27. }
  28. const device = await OcrDevice.findBy('id', data.id)
  29. if (device) {
  30. device.merge(data)
  31. return await device.save()
  32. } else {
  33. return await OcrDevice.create(data)
  34. }
  35. }
  36. public async show({ params }: HttpContextContract) {
  37. return await OcrDevice.findOrFail(params.id)
  38. }
  39. public async plusTotal({ request, response }: HttpContextContract) {
  40. try {
  41. const device = await OcrDevice.findBy('id', request.param('id'))
  42. if (!device) {
  43. return response.notFound({ message: `未找到ID为 ${request.param('id')} 的OCR设备` })
  44. }
  45. device.total += 1
  46. await device.save()
  47. return response.ok(device)
  48. } catch (error) {
  49. return response.internalServerError({
  50. message: '更新设备记录数量时发生错误',
  51. error: error.message
  52. })
  53. }
  54. }
  55. public async plusScanned({ request, response }: HttpContextContract) {
  56. const scanCount = Number(request.param('scanCount'))
  57. if (isNaN(scanCount)) {
  58. return response.badRequest({ message: 'scanCount 参数必须是有效数字' })
  59. }
  60. try {
  61. const device = await OcrDevice.findBy('id', request.param('id'))
  62. if (!device) {
  63. return response.notFound({
  64. message: `未找到 ID 为 ${request.param('id')} 的 OCR 设备`
  65. })
  66. }
  67. device.scanned += scanCount
  68. await device.save()
  69. return response.ok(device)
  70. } catch (error) {
  71. return response.internalServerError({
  72. message: '更新设备扫描数量时发生错误',
  73. error: error.message
  74. })
  75. }
  76. }
  77. }