codeUtil.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. export class CodeUtil {
  2. codeType = []
  3. constructor(codeType) {
  4. if (!Array.isArray(codeType)) {
  5. console.error('codeType should be an array')
  6. return
  7. }
  8. this.codeType = codeType
  9. }
  10. scan(options = {}) {
  11. return uni.scanCode(options)
  12. }
  13. async getCodeInfo(options) {
  14. const { scanType, result } = await this.scan(options)
  15. return this.parseCode(result)
  16. }
  17. makeCode(type, content) {
  18. const t = this.codeType.indexOf(type)
  19. if (t == -1) {
  20. console.error(`codeType ${type} is undefined`, this.codeType)
  21. return null
  22. }
  23. return JSON.stringify({
  24. t,
  25. c: content
  26. })
  27. }
  28. parseCode(codeInfo) {
  29. try {
  30. const info = JSON.parse(codeInfo)
  31. const { t, c } = info
  32. const type = this.codeType[t]
  33. if (type) return { type, content: c }
  34. return { type: 'unknown', content: info }
  35. } catch (err) {
  36. console.error('parseCode error', err)
  37. return { type: 'error', content: codeInfo }
  38. }
  39. }
  40. }
  41. export const codeUtil = new CodeUtil([])