cities.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. import Cities from '../../models/v1/cities';
  3. import http from 'http';
  4. import pinyin from "pinyin";
  5. import BaseComponent from '../../prototype/baseComponent'
  6. class CityHandle extends BaseComponent{
  7. constructor(){
  8. super()
  9. this.getCity = this.getCity.bind(this);
  10. }
  11. async getCity(req, res, next){
  12. const type = req.query.type;
  13. let cityInfo;
  14. try{
  15. switch (type){
  16. case 'guess':
  17. const city = await this.getCityName(req);
  18. cityInfo = await Cities.cityGuess(city);
  19. break;
  20. case 'hot':
  21. cityInfo = await Cities.cityHot();
  22. break;
  23. case 'group':
  24. cityInfo = await Cities.cityGroup();
  25. break;
  26. default:
  27. res.json({
  28. name: 'ERROR_QUERY_TYPE',
  29. message: '参数错误',
  30. })
  31. return
  32. }
  33. res.send(cityInfo);
  34. }catch(err){
  35. res.send(err);
  36. }
  37. }
  38. async getCityById(req, res, next){
  39. const cityid = req.params.id;
  40. if (isNaN(cityid)) {
  41. res.json({
  42. name: 'ERROR_PARAM_TYPE',
  43. message: '参数错误',
  44. })
  45. return
  46. }
  47. try{
  48. const cityInfo = await Cities.getCityById(cityid);
  49. res.send(cityInfo);
  50. }catch(err){
  51. res.send(err);
  52. }
  53. }
  54. getCityName(req){
  55. return new Promise(async (resolve, reject) => {
  56. let ip = req.headers['x-forwarded-for'] ||
  57. req.connection.remoteAddress ||
  58. req.socket.remoteAddress ||
  59. req.connection.socket.remoteAddress;
  60. const ipArr = ip.split(':');
  61. ip = ipArr[ipArr.length -1];
  62. ip = '116.231.55.195';
  63. /*
  64. 调用新浪接口,获取ip地址信息
  65. */
  66. const url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php';
  67. let res = await this.fetch('GET', url , {format: 'js', ip,}, 'TEXT');
  68. const cityInfo = JSON.parse(res.split('=')[1].toString().replace(';', ''));
  69. /*
  70. 汉字转换成拼音
  71. */
  72. const pinyinArr = pinyin(cityInfo.city, {
  73. style: pinyin.STYLE_NORMAL,
  74. });
  75. let cityName = '';
  76. pinyinArr.forEach(item => {
  77. cityName += item[0];
  78. })
  79. resolve(cityName)
  80. })
  81. }
  82. }
  83. export default new CityHandle()