cities.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. import Cities from '../../models/v1/cities';
  3. import pinyin from "pinyin";
  4. import BaseComponent from '../../prototype/baseComponent'
  5. class CityHandle extends BaseComponent{
  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. getCityName(req){
  54. return new Promise(async (resolve, reject) => {
  55. let ip = req.headers['x-forwarded-for'] ||
  56. req.connection.remoteAddress ||
  57. req.socket.remoteAddress ||
  58. req.connection.socket.remoteAddress;
  59. const ipArr = ip.split(':');
  60. ip = ipArr[ipArr.length -1];
  61. if (process.env.NODE_ENV == 'development') {
  62. ip = '116.231.55.195';
  63. }
  64. /*
  65. 调用新浪接口,获取ip地址信息
  66. */
  67. const url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php';
  68. let res = await this.fetch(url , {format: 'js', ip,}, 'GET', 'TEXT');
  69. const cityInfo = JSON.parse(res.split('=')[1].toString().replace(';', ''));
  70. /*
  71. 汉字转换成拼音
  72. */
  73. const pinyinArr = pinyin(cityInfo.city, {
  74. style: pinyin.STYLE_NORMAL,
  75. });
  76. let cityName = '';
  77. pinyinArr.forEach(item => {
  78. cityName += item[0];
  79. })
  80. resolve(cityName)
  81. })
  82. }
  83. }
  84. export default new CityHandle()