Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"@netlify/build": "34.2.3",
"@netlify/build-info": "10.0.7",
"@netlify/config": "23.1.0",
"@netlify/dev-utils": "^3.2.2",
"@netlify/edge-bundler": "14.2.1",
"@netlify/edge-functions": "2.15.6",
"@netlify/headers-parser": "9.0.1",
Expand Down
27 changes: 2 additions & 25 deletions src/lib/geo-location.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import fetch from 'node-fetch'
import { Geolocation, mockLocation } from '@netlify/dev-utils'

const API_URL = 'https://netlifind.netlify.app'
const STATE_GEO_PROPERTY = 'geolocation'
Expand All @@ -8,35 +9,11 @@ const CACHE_TTL = 8.64e7
// 10 seconds
const REQUEST_TIMEOUT = 1e4

export type Geolocation = {
city: string
country: {
code: string
name: string
}
subdivision: {
code: string
name: string
}
longitude: number
latitude: number
timezone: string
}

interface State {
get(key: string): unknown
set(key: string, value: unknown): void
}

export const mockLocation: Geolocation = {
city: 'San Francisco',
country: { code: 'US', name: 'United States' },
subdivision: { code: 'CA', name: 'California' },
longitude: 0,
latitude: 0,
timezone: 'UTC',
}

/**
* Returns geolocation data from a remote API, the local cache, or a mock location, depending on the
* specified mode.
Expand All @@ -63,7 +40,7 @@ export const getGeoLocation = async ({
// `cache`, let's try to use it.
// Or, if the country we're trying to mock is the same one as we have in the
// cache, let's use the cache instead of the mock.
if (cacheObject !== undefined && (mode === 'cache' || cacheObject.data.country.code === geoCountry)) {
if (cacheObject !== undefined && (mode === 'cache' || cacheObject.data.country?.code === geoCountry)) {
const age = Date.now() - cacheObject.timestamp

// Let's use the cached data if it's not older than the TTL. Also, if the
Expand Down
3 changes: 2 additions & 1 deletion tests/unit/lib/geo-location.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import nock from 'nock'
import { describe, expect, test } from 'vitest'

import { type Geolocation, getGeoLocation, mockLocation } from '../../../src/lib/geo-location.js'
import { Geolocation, mockLocation } from '@netlify/dev-utils'
import { getGeoLocation } from '../../../src/lib/geo-location.js'

describe('getGeoLocation', () => {
test('returns geolocation data from the API if `mode: "cache"`', async () => {
Expand Down