cities.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. import Cities from '../../models/v1/cities';
  3. import pinyin from "pinyin";
  4. import AddressComponent from '../../prototype/addressComponent'
  5. class CityHandle extends AddressComponent{
  6. constructor(){
  7. super()
  8. this.getCity = this.getCity.bind(this);
  9. }
  10. async getCity(req, res, next){
  11. const type = req.query.type;
  12. let cityInfo;
  13. try{
  14. switch (type){
  15. case 'guess':
  16. const city = await this.getCityName(req);
  17. cityInfo = await Cities.cityGuess(city);
  18. break;
  19. case 'hot':
  20. cityInfo = await Cities.cityHot();
  21. break;
  22. case 'group':
  23. cityInfo = await Cities.cityGroup();
  24. break;
  25. default:
  26. res.json({
  27. name: 'ERROR_QUERY_TYPE',
  28. message: '参数错误',
  29. })
  30. return
  31. }
  32. res.send(cityInfo);
  33. }catch(err){
  34. res.send(err);
  35. }
  36. }
  37. async getCityById(req, res, next){
  38. const cityid = req.params.id;
  39. if (isNaN(cityid)) {
  40. res.json({
  41. name: 'ERROR_PARAM_TYPE',
  42. message: '参数错误',
  43. })
  44. return
  45. }
  46. try{
  47. const cityInfo = await Cities.getCityById(cityid);
  48. res.send(cityInfo);
  49. }catch(err){
  50. res.send(err);
  51. }
  52. }
  53. async getCityName(req){
  54. let cityInfo;
  55. try{
  56. cityInfo = await this.guessPosition(req);
  57. }catch(err){
  58. console.error()
  59. }
  60. /*
  61. 汉字转换成拼音
  62. */
  63. const pinyinArr = pinyin(cityInfo.city, {
  64. style: pinyin.STYLE_NORMAL,
  65. });
  66. let cityName = '';
  67. pinyinArr.forEach(item => {
  68. cityName += item[0];
  69. })
  70. return cityName
  71. }
  72. }
  73. export default new CityHandle()