cities.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. import Cities from '../../models/v1/cities';
  3. import http from 'http';
  4. import pinyin from "pinyin";
  5. import fetch from 'node-fetch';
  6. class CityHandle {
  7. constructor(){
  8. this.cityGuess = this.cityGuess.bind(this);
  9. }
  10. async cityGuess(req, res, next){
  11. const type = req.query.type;
  12. if (!type) {
  13. res.json({
  14. name: 'ERROR_QUERY_TYPE',
  15. message: '参数错误',
  16. })
  17. return
  18. }
  19. let cityInfo;
  20. switch (type){
  21. case 'guess':
  22. const city = await this.getCityName(req);
  23. cityInfo = await Cities.cityGuess(city);
  24. break;
  25. case 'hot':
  26. cityInfo = await Cities.cityHot();
  27. break;
  28. case 'group':
  29. cityInfo = await Cities.cityGroup();
  30. break;
  31. }
  32. res.send(cityInfo)
  33. }
  34. getCityName(req){
  35. return new Promise(async (resolve, reject) => {
  36. let ip = req.headers['x-forwarded-for'] ||
  37. req.connection.remoteAddress ||
  38. req.socket.remoteAddress ||
  39. req.connection.socket.remoteAddress;
  40. const ipArr = ip.split(':');
  41. ip = ipArr[ipArr.length -1];
  42. // ip = '116.231.55.195';
  43. /*
  44. 调用新浪接口,获取ip地址信息
  45. */
  46. const url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' + ip;
  47. let res;
  48. try{
  49. res = await fetch(url);
  50. res = await res.text();
  51. }catch(err){
  52. console.log(err)
  53. }
  54. const cityInfo = JSON.parse(res.split('=')[1].toString().replace(';', ''))
  55. const pinyinArr = pinyin(cityInfo.city, {
  56. style: pinyin.STYLE_NORMAL,
  57. });
  58. let city = '';
  59. pinyinArr.forEach(item => {
  60. city += item[0];
  61. })
  62. resolve(city)
  63. })
  64. }
  65. }
  66. export default new CityHandle()