This repository demonstrates a simple implementation of the Repository Pattern using Nuxt 3, TypeScript, and NitroPack for fetching data from an API.
app.vue
The main component of the application, where the user data is fetched and displayed.
@/repository/user: User repository module.
~/types/user: User type definition.
- Sets up the page title using the useHead function.
- Initializes the user repository with the API using userRepository($api).
- Fetches and displays a list of users on component mount.
<script setup lang="ts">
// ... (imports and setup)
const { $api } = useNuxtApp()
const userReposity = userRepository($api)
const users: Ref<User[]> = ref([])
const fetchUsers = async () => {
try {
users.value = await userReposity.get()
} catch (error: any) {
throw new Error(error)
}
}
onBeforeMount(() => fetchUsers())
</script>
<template>
<!-- ... (template to display user list) -->
</template>
repository/user.ts
The user repository module responsible for fetching user data from the API.
- nitropack: NitroPack fetch utility.
- ~/types/user: User type definition.
- userRepository: Function that initializes the user repository.
// ... (imports)
export const userRepository = <T>(fetch: $Fetch<T, NitroFetchRequest>) => ({
async get(): Promise<User[]> {
return fetch('/users')
}
})
plugin/api.ts
Nuxt plugin to set up the API client using NitroPack's $fetch.
- nitropack: NitroPack fetch utility.
- useRuntimeConfig: Nuxt runtime configuration.
Nuxt plugin that provides the configured API instance.
// ... (imports)
export default defineNuxtPlugin({
setup() {
const api = $fetch.create({
baseURL: useRuntimeConfig().public.apiUrl
// add more options here
})
return {
provide: { api }
}
}
})
- Install dependencies:
pnpm install
- Run the application:
pnpm dev
- Open your browser and visit http://localhost:3000 to see the application in action.
Feel free to adapt and extend this example for your own projects.