cities.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. //ip = '116.231.55.195';
  62. /*
  63. 调用新浪接口,获取ip地址信息
  64. */
  65. const url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php';
  66. let res = await this.fetch(url , {format: 'js', ip,}, 'GET', 'TEXT');
  67. const cityInfo = JSON.parse(res.split('=')[1].toString().replace(';', ''));
  68. /*
  69. 汉字转换成拼音
  70. */
  71. const pinyinArr = pinyin(cityInfo.city, {
  72. style: pinyin.STYLE_NORMAL,
  73. });
  74. let cityName = '';
  75. pinyinArr.forEach(item => {
  76. cityName += item[0];
  77. })
  78. resolve(cityName)
  79. })
  80. }
  81. }
  82. export default new CityHandle()