Skip to content

Commit

Permalink
feat: ip api service
Browse files Browse the repository at this point in the history
  • Loading branch information
hywax committed Feb 1, 2024
1 parent 7b849bd commit fe4a219
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
19 changes: 19 additions & 0 deletions components/service/IpApi.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<template>
<ServiceBase v-bind="props">
<template v-if="props.options?.flagIcon !== false" #icon="{ service }">
<ServiceBaseIcon :name="`flag:${service?.data?.country}-1x1`" />
</template>
<template #title="{ service }">
{{ service?.data?.ip || '' }}
</template>
<template #description="{ service }">
{{ service?.data?.place || '' }}
</template>
</ServiceBase>
</template>

<script setup lang="ts">
import type { IpApiService, ServiceClient } from '~/types'
const props = defineProps<ServiceClient<IpApiService>>()
</script>
37 changes: 37 additions & 0 deletions server/api/services/ip-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { IpApiService } from '~/types'
import { getServiceWithDefaultData, returnServiceWithData } from '~/server/utils/services'

interface IpApiFetchResponse {
status: string
country: string
countryCode: string
region: string
regionName: string
city: string
zip: string
lat: number
lon: number
timezone: string
isp: string
org: string
as: string
query: string
}

const cachedIpApiData = defineCachedFunction(async (lang: string = 'en') => {
const response = await $fetch<IpApiFetchResponse>(`http://ip-api.com/json/?lang=${lang}`)

return {
ip: response.query,
place: `${response.city}, ${response.regionName}`,
country: response.countryCode.toLowerCase(),
}
}, { maxAge: 60 * 24 })

export default defineEventHandler(async (event) => {
const service = await getServiceWithDefaultData<IpApiService>(event)
const config = await getLocalConfig()
const ip = await cachedIpApiData(config?.lang)

return returnServiceWithData(service, ip)
})
10 changes: 10 additions & 0 deletions types/services.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,13 @@ export interface ServiceWithDefaultData<S> {
export type ReturnServiceWithData<D, S extends ServiceWithDefaultData<Service>['defaultData']> = S & { data: D }

export interface BaseService extends Service {}

export interface IpApiService extends Service {
options?: {
flagIcon?: boolean
}
server: {
ip: string
place: string
}
}

0 comments on commit fe4a219

Please sign in to comment.