vue-crud-api
v1.2.0
Published
A lightweight Vue 3 + Nuxt 3 CRUD composables library with Axios and Auth support.
Maintainers
Readme
# vue-crud-api
A Vue 3 / Nuxt 3 composable library that simplifies REST API CRUD operations with built-in authentication handling, automatic token refresh, and toast notifications. This library helps you manage API requests with ease, handle authentication tokens, and display notifications automatically.
---
## Installation
```bash
npm install vue-crud-api axios vue-toastification
# or
yarn add vue-crud-api axios vue-toastification
```Usage
Setup
Import and initialize useApi and useAuth by providing the required dependencies:
import { useApi, useAuth } from "vue-crud-api";
import { useRouter } from "vue-router";
import { useToast } from "vue-toastification";
const router = useRouter();
const toast = useToast();
const authConfig = {
baseUrl: "https://your-api.com/api",
loginEndpoint: "auth/login",
refreshTokenEndPoint: "auth/refresh-token",
key: "app-user",
};
const { GET, POST, DELETE } = useApi({ router, authConfig, toast });
const auth = useAuth(authConfig, router);API
useApi Parameters
router(Vue Router instance): For navigation and redirection.authConfig(object):baseUrl(string): Base API URL.loginEndpoint(string): Login endpoint.refreshTokenEndPoint(string): Token refresh endpoint.key(string): Unique localStorage key for user data.
toast(Vue Toastification instance): For notifications.defaultNotifications(optional): Default notification messages for all requests.
HTTP Methods
GET
GET<T>(url: string, params?: Record<string, any>): Promise<AxiosResponse<T>>- Generic type
Tfor expected response data. - Optional
paramsto send as query parameters. - Note: This method does not trigger toast notifications by default.
POST
POST<ResT, ReqT>(
url: string,
body: ReqT,
notifications?: NotificationsType,
config?: AxiosRequestConfig & { formData?: boolean }
): Promise<AxiosResponse<ResT>>- Supports generic request and response types.
notificationscontrols success, error, and confirmation toasts.- To send FormData (files etc.), use
{ formData: true }in config.
DELETE
DELETE(
url: string,
body: any,
params?: Record<string, any>,
notifications?: NotificationsType,
config?: AxiosRequestConfig
): Promise<any>- Supports optional request body and query params.
- Notifications customizable like other methods.
NotificationsType Interface
interface NotificationsType {
error?: string | boolean; // true for default, string for custom error message
success?: string | boolean; // true for default, string for custom success message
confirm?: any | boolean; // confirmation dialog config or false to disable
}Example usage with custom messages:
await POST("/items", item, {
success: "Item added successfully!",
error: "Failed to add item.",
confirm: false,
});Error Handling
- Errors trigger toast notifications if
erroris true or a string. - You can catch errors for custom handling:
try {
await GET("/data");
} catch (error) {
console.error("Custom error handling:", error);
}useAuth Composable
Provides authentication-related methods:
Login(credentials: { login: string; password: string }): Performs login.LogOut(redirectPath?: string): Logs out and redirects (default/auth/login).RefreshToken(): Refreshes the access token using stored refresh token.IsLoggedIn(): Returns a boolean indicating authentication status.GetAccessToken(): Retrieves current JWT access token.SetUserData(data: any): Stores user data locally.GetUserData(): Retrieves stored user data.
Example login:
await auth.Login({ login: "user", password: "pass" });
if (auth.IsLoggedIn()) {
const token = auth.GetAccessToken();
}useCrudApi Composable - Dynamic and Optional Parameters Usage
The useCrudApi composable simplifies CRUD operations for a resource and supports dynamic endpoints, optional parameters, and customizable notifications.
Basic Setup
const api = useApi({ router, authConfig, toast });
const crud = useCrudApi("resourceName", api);Methods & Usage
getAll(params?, customEndpoint?, notifications?)
Fetches all items. params and notifications are optional.
const allItems = await crud.getAll({ page: 1 }); // Default endpoint: /resourceName
const allItemsCustom = await crud.getAll(undefined, "/custom-resource", {
success: "Loaded successfully!",
});getNames(customEndpoint?, params?, notifications?)
Fetches resource names or identifiers. Defaults to /resourceName/names.
const names = await crud.getNames();
const namesCustom = await crud.getNames(
"/users/usernames",
{ active: true },
{
success: "Names fetched!",
}
);getOne(id, params?, customEndpoint?, notifications?)
Fetch a single item by ID with optional query params and dynamic endpoint.
const item = await crud.getOne(123);
const itemWithParams = await crud.getOne(123, { includeDetails: true });
const itemCustom = await crud.getOne(
123,
undefined,
(id) => `/custom-items/${id}`
);
const itemWithNotify = await crud.getOne(123, undefined, undefined, {
success: "Item loaded!",
});create(data, notifications?, config?, customEndpoint?)
Create a new item, optionally as FormData, with custom notifications and endpoint.
const newItem = await crud.create({ name: "New Item" });
const newItemFormData = await crud.create(formDataObject, undefined, {
formData: true,
});
const newItemWithNotify = await crud.create(
{ name: "Notify" },
{ success: "Created!" }
);
const newItemCustom = await crud.create(
{ name: "Custom" },
undefined,
undefined,
"/custom-create"
);update(id, data, notifications?, config?, customEndpoint?)
Update an item by ID with optional config, notifications, and dynamic endpoint.
const updated = await crud.update(123, { name: "Updated" });
const updatedFormData = await crud.update(123, formDataObject, undefined, {
formData: true,
});
const updatedCustom = await crud.update(
123,
{ name: "Custom" },
undefined,
undefined,
(id) => `/custom-items/${id}/edit`
);
const updatedNotify = await crud.update(
123,
{ name: "Notify" },
{ success: "Updated!" }
);remove(id, notifications?, params?, config?, customEndpoint?)
Delete an item by ID, optionally with notifications, query params, config, and custom endpoint.
await crud.remove(123);
await crud.remove(123, {
confirm: {
title: "Are you sure?",
text: "This action cannot be undone!",
confirmButtonText: "Yes, delete",
cancelButtonText: "Cancel",
},
success: "Deleted!",
});
await crud.remove(
123,
undefined,
{ softDelete: true },
{ headers: { Authorization: "Bearer token" } }
);
await crud.remove(
123,
undefined,
undefined,
undefined,
(id) => `/custom-delete/${id}`
);Contributing
Contributions, issues, and feature requests are welcome! Feel free to submit pull requests.
License
MIT © Ali Sayed
