utils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const fs = require('fs')
  2. const path = require('path')
  3. /**
  4. * @param {string} url
  5. * @returns {Object}
  6. */
  7. function param2Obj(url) {
  8. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  9. if (!search) {
  10. return {}
  11. }
  12. const obj = {}
  13. const searchArr = search.split('&')
  14. searchArr.forEach(v => {
  15. const index = v.indexOf('=')
  16. if (index !== -1) {
  17. const name = v.substring(0, index)
  18. const val = v.substring(index + 1, v.length)
  19. obj[name] = val
  20. }
  21. })
  22. return obj
  23. }
  24. /**
  25. * This is just a simple version of deep copy
  26. * Has a lot of edge cases bug
  27. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  28. * @param {Object} source
  29. * @returns {Object}
  30. */
  31. function deepClone(source) {
  32. if (!source && typeof source !== 'object') {
  33. throw new Error('error arguments', 'deepClone')
  34. }
  35. const targetObj = source.constructor === Array ? [] : {}
  36. Object.keys(source).forEach(keys => {
  37. if (source[keys] && typeof source[keys] === 'object') {
  38. targetObj[keys] = deepClone(source[keys])
  39. } else {
  40. targetObj[keys] = source[keys]
  41. }
  42. })
  43. return targetObj
  44. }
  45. function getDB (type) {
  46. try {
  47. return JSON.parse(fs.readFileSync(`./mock/${type}/db.json`))
  48. } catch (e) {
  49. return []
  50. }
  51. }
  52. function saveDB (type, db) {
  53. fs.writeFileSync(`./mock/${type}/db.json`, JSON.stringify(db))
  54. }
  55. module.exports = {
  56. param2Obj,
  57. deepClone,
  58. getDB,
  59. saveDB
  60. }