searchSql.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const {toNumber} = require("../tools/typeTool");
  2. const {handle} = require("./handle");
  3. const codeMap = require("../map/rcodeMap");
  4. function limitSql (limit = 20,page = 1){
  5. let sql = '';
  6. let values = [];
  7. limit = toNumber(limit);
  8. page = toNumber(page);
  9. limit = limit || 20;
  10. page = page || 1;
  11. sql += ` limit ?,?`;
  12. values.push(limit * (page - 1),limit)
  13. return {sql,values}
  14. }
  15. /**
  16. * 封装搜索数据库字段
  17. * @param errorText
  18. * @param dbFn
  19. * @param _params
  20. * @param page
  21. * @param limit
  22. * @returns {Promise<[err,{arr, total: number, limit, page}]>}
  23. */
  24. async function searchHandle(errorText,dbFn,_params,page,limit){
  25. let err,response,arrPromise,countPromise;
  26. limit = toNumber(limit);
  27. page = toNumber(page);
  28. limit = limit||20;
  29. page = page||1;
  30. arrPromise = dbFn('array',_params,page,limit);
  31. if(page <= 1){
  32. // 添加计数字段
  33. countPromise = dbFn('count',_params);
  34. [err,response] = await handle(Promise.all([arrPromise,countPromise]))
  35. }else{
  36. [err,response] = await handle(Promise.all([arrPromise]))
  37. }
  38. if(err){
  39. console.log(err);
  40. return [
  41. {eCode:codeMap.ServerError,eMsg:`${errorText}`},
  42. null
  43. ]
  44. }
  45. let result = {
  46. arr: response[0],
  47. limit: limit,
  48. page: page,
  49. total: 0
  50. }
  51. if(page <= 1){
  52. result.total = response[1]?response[1][0].total:null
  53. }
  54. return [null,result];
  55. }
  56. function searchSql (fn,type,sql,values,limit,page){
  57. // 添加分页
  58. if(type==='array'){
  59. let _limitSql = limitSql(limit,page);
  60. sql += _limitSql.sql;
  61. values.push(..._limitSql.values);
  62. }
  63. return fn(sql,values)
  64. }
  65. module.exports = {
  66. limitSql,
  67. searchHandle,
  68. searchSql
  69. }