cities.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. console.log(cityInfo)
  58. }catch(err){
  59. console.error()
  60. }
  61. /*
  62. 汉字转换成拼音
  63. */
  64. const pinyinArr = pinyin(cityInfo.city, {
  65. style: pinyin.STYLE_NORMAL,
  66. });
  67. let cityName = '';
  68. pinyinArr.forEach(item => {
  69. cityName += item[0];
  70. })
  71. return cityName
  72. }
  73. }
  74. export default new CityHandle()