cities.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. ip = "116.231.55.195";
  42. //调用新浪接口
  43. http.get('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' + ip,
  44. (req,res) => {
  45. let data;
  46. req.on('data',res => {
  47. res = res.toString();
  48. const subIndex = res.indexOf('city');
  49. data = res.substring(subIndex,res.indexOf(',', subIndex));
  50. data = data.split(':')[1].replace(/"/gi, '');
  51. });
  52. req.on('end',() => {
  53. data = unescape(data.replace(/\\u/g, '%u'));
  54. data = pinyin(data, {
  55. style: pinyin.STYLE_NORMAL,
  56. });
  57. let city = '';
  58. data.forEach(item => {
  59. city += item[0];
  60. })
  61. resolve(city)
  62. });
  63. });
  64. })
  65. }
  66. }
  67. export default new CityHandle()