cities.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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.cityGuess = this.cityGuess.bind(this);
  10. }
  11. async cityGuess(req, res, next){
  12. const type = req.query.type;
  13. if (!type) {
  14. res.json({
  15. name: 'ERROR_QUERY_TYPE',
  16. message: '参数错误',
  17. })
  18. return
  19. }
  20. let cityInfo;
  21. switch (type){
  22. case 'guess':
  23. const city = await this.getCityName(req);
  24. cityInfo = await Cities.cityGuess(city);
  25. break;
  26. case 'hot':
  27. cityInfo = await Cities.cityHot();
  28. break;
  29. case 'group':
  30. cityInfo = await Cities.cityGroup();
  31. break;
  32. }
  33. res.send(cityInfo)
  34. }
  35. getCityName(req){
  36. return new Promise(async (resolve, reject) => {
  37. let ip = req.headers['x-forwarded-for'] ||
  38. req.connection.remoteAddress ||
  39. req.socket.remoteAddress ||
  40. req.connection.socket.remoteAddress;
  41. const ipArr = ip.split(':');
  42. ip = ipArr[ipArr.length -1];
  43. ip = '116.231.55.195';
  44. /*
  45. 调用新浪接口,获取ip地址信息
  46. */
  47. const url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php';
  48. let res = await this.fetch('GET', url , {format: 'js', ip,}, 'TEXT');
  49. const cityInfo = JSON.parse(res.split('=')[1].toString().replace(';', ''));
  50. /*
  51. 汉字转换成拼音
  52. */
  53. const pinyinArr = pinyin(cityInfo.city, {
  54. style: pinyin.STYLE_NORMAL,
  55. });
  56. let cityName = '';
  57. pinyinArr.forEach(item => {
  58. cityName += item[0];
  59. })
  60. resolve(cityName)
  61. })
  62. }
  63. }
  64. export default new CityHandle()