Added device collection.

This commit is contained in:
Mike Cao 2020-08-06 19:14:44 -07:00
parent 6e23a8a53b
commit e17c9da3d5
6 changed files with 389 additions and 310 deletions

View file

@ -3,6 +3,7 @@ import { browserName, detectOS } from 'detect-browser';
import isLocalhost from 'is-localhost-ip';
import maxmind from 'maxmind';
import geolite2 from 'geolite2-redist';
import { DESKTOP_OS, MOBILE_OS, DESKTOP_SCREEN_WIDTH, MOBILE_SCREEN_WIDTH } from './constants';
export function getIpAddress(req) {
// Cloudflare
@ -13,12 +14,20 @@ export function getIpAddress(req) {
return requestIp.getClientIp(req);
}
export function getDevice(req) {
const userAgent = req.headers['user-agent'];
const browser = browserName(userAgent);
const os = detectOS(userAgent);
export function getDevice(screen, browser, os) {
const [width] = screen.split('x');
return { userAgent, browser, os };
if (DESKTOP_OS.includes(os)) {
if (os === 'Chrome OS' || width < DESKTOP_SCREEN_WIDTH) {
return 'laptop';
}
return 'desktop';
} else if (MOBILE_OS.includes(os)) {
if (os === 'Amazon OS' || width < MOBILE_SCREEN_WIDTH) {
return 'tablet';
}
return 'mobile';
}
}
export async function getCountry(req, ip) {
@ -43,3 +52,14 @@ export async function getCountry(req, ip) {
return result.country.iso_code;
}
export async function getClientInfo(req, { screen }) {
const ip = getIpAddress(req);
const country = await getCountry(req, ip);
const userAgent = req.headers['user-agent'];
const browser = browserName(userAgent);
const os = detectOS(userAgent);
const device = getDevice(screen, browser, os);
return { userAgent, browser, os, ip, country, device };
}