cities.js 1.7 KB

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