Skip to content

fix auto import and upgrade the README.md #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 24, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
143 changes: 66 additions & 77 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@

## ✨ Features

- 📦 Resource-based client
- 🔍 Search, details, mutate, actions, and delete Methods
- 🛠️ Auto-imported resources in Nuxt 3
- 🧩 TypeScript support for better developer experience
- 🔄 Hooks for request and response handling
- 🌍 Works seamlessly with Nuxt 3 and TypeScript
- 📦 Resource-based client
- 🔍 Search, details, mutate, actions, and delete Methods
- 🛠️ Auto-imported resources in Nuxt 3
- 🧩 TypeScript support for better developer experience
- 🔄 Hooks for request and response handling
- 🌍 Works seamlessly with Nuxt 3 and TypeScript

---

Expand All @@ -35,8 +35,8 @@ and then add it to your Nuxt 3 project by adding it to your `nuxt.config.ts`:
```typescript
// nuxt.config.ts
export default defineNuxtConfig({
modules: ["laravel-rest-api-nuxt-sdk"],
// other configurations...
modules: ["laravel-rest-api-nuxt-sdk"],
// other configurations...
});
```

Expand All @@ -47,24 +47,21 @@ to use the Laravel REST API SDK, you need to configure it in your Nuxt 3 applica
```typescript
// plugins/restApiSdk.ts
export default defineNuxtPlugin(() => {
const restApiSdk = useNuxtApp().$restApiSdk;
restApiSdk.setGlobalFetchOptions({
baseURL: "https://localhost/api",
onRequest: ({ options }) => {
const access_token = useCookie("cookie");
options.headers.set(
"Authorization",
`Bearer ${access_token.value}`
);
},
});
const restApiSdk = useNuxtApp().$restApiSdk;
restApiSdk.setGlobalFetchOptions({
baseURL: "https://localhost/api",
onRequest: ({ options }) => {
const access_token = useCookie("cookie");
options.headers.set("Authorization", `Bearer ${access_token.value}`);
},
});
});
```

explanation:

- `baseURL`: The base URL of your Laravel REST API.
- `onRequest`: Lets you modify request options before sending, e.g., adding an `Authorization` header from a cookie.
- `baseURL`: The base URL of your Laravel REST API.
- `onRequest`: Lets you modify request options before sending, e.g., adding an `Authorization` header from a cookie.

> **Tip:** The SDK uses `ofetch` from Nuxt under the hood, so you can configure many options in the `setGlobalFetchOptions` method. For more details, refer to the [ofetch documentation](https://github.com/unjs/ofetch).

Expand All @@ -77,36 +74,28 @@ The `defineResource<T>(resourceName, resourcePreset?)` composable returns an obj
> **Tip:** All resources in the `resources` folder are auto-imported by Nuxt, so you can use them directly in your components without manual imports.

```ts
// resources/products.ts

export const useProducts = defineResource<IProducts>("products", {
onRequest: ({ options }) => {
const access_token = useCookie("cookie");
options.headers.set("Authorization", `Bearer ${access_token.value}`);
},
onResponse: ({ response }) => {
toast.success("Request successful!");
},
//...
});
// resources/useProducts.ts
export default defineResource<IProducts>("products");
```

//you can also define presets for the search method, like relations, filters, etc.
export const useProducts = defineResource<IProducts>("products", {
search: {
includes: [
{
relation: "category",
},
{
relation: "star",
},
],
},
//...
You can also define presets for the search method, like relations, filters, etc.

```ts
export default defineResource<IProducts>("products", {
search: {
includes: [
{
relation: "category",
},
{
relation: "star",
},
],
},
});
```

> ⚠️ **Note:** The `baseURL` specified here will not override the global configuration. Hooks such as `onRequest` and `onResponse` will be merged with the global settings, not replace them.
> ℹ️ **Note:** Options defined in `setGlobalFetchOptions` can be overridden here for each resource, except for `baseURL` which always remains global. Hooks (`onRequest`, `onResponse`, etc.) will be merged with the global ones.

## <a id="methods"></a> 🧩 Methods

Expand All @@ -128,20 +117,20 @@ Search for resources based on the request parameters. (See [Search](https://lara
```ts
const productsResource = useProducts();
const res = await productsResource
.search({
filters: [
{
field: "name",
name: "Product Name",
},
],
includes: [
{
relation: "category",
},
],
})
.catch((err) => console.error("Error during search: ", err));
.search({
filters: [
{
field: "name",
name: "Product Name",
},
],
includes: [
{
relation: "category",
},
],
})
.catch((err) => console.error("Error during search: ", err));
```

### ✏️ `mutate(mutations)`
Expand All @@ -151,19 +140,19 @@ Mutate a resource with the provided mutations. (See [Mutate](https://laravel-res
```ts
const productsResource = useProducts();
const response = await productsResource
.mutate([
{
operation: "update",
key: 2,
relations: {
star: {
operation: "attach",
key: 1,
},
},
},
])
.catch((err) => console.error("Error during mutation: ", err));
.mutate([
{
operation: "update",
key: 2,
relations: {
star: {
operation: "attach",
key: 1,
},
},
},
])
.catch((err) => console.error("Error during mutation: ", err));
```

### ⚙️ `actions(actionName, params?)`
Expand All @@ -173,9 +162,9 @@ Execute a specific action on a resource. (See [Actions](https://laravel-rest-api
```ts
const productsResource = useProducts();
const response = await productsResource.actions("publish", {
search: {
filters: [{ field: "id", value: 1 }],
},
search: {
filters: [{ field: "id", value: 1 }],
},
});
```

Expand Down
65 changes: 35 additions & 30 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,38 @@
import { defineNuxtModule, createResolver, addImportsDir, addPlugin } from '@nuxt/kit'
import {
defineNuxtModule,
createResolver,
addImportsDir,
addPlugin,
} from "@nuxt/kit";

export default defineNuxtModule({
meta: {
name: 'laravel-rest-api-nuxt-sdk',
configKey: 'restApiSdk'
},
setup(_, nuxt) {
const resolver = createResolver(import.meta.url);
addImportsDir(resolver.resolve('./runtime/defineResource'));
addPlugin(resolver.resolve('./runtime/plugin'));
meta: {
name: "laravel-rest-api-nuxt-sdk",
configKey: "restApiSdk",
},
setup(_, nuxt) {
const resolver = createResolver(import.meta.url);
addImportsDir(resolver.resolve("./runtime/defineResource"));
addImportsDir(nuxt.options.srcDir + "/resources");
addPlugin(resolver.resolve("./runtime/plugin"));

nuxt.hook('prepare:types', (opts) => {
const typesDir = './runtime/types/'
if (!Array.isArray(opts.references)) {
opts.references = []
}
opts.references.push({
path: resolver.resolve(`${typesDir}restApiSdk.d.ts`)
})
opts.references.push({
path: resolver.resolve(`${typesDir}actions.d.ts`)
})
opts.references.push({
path: resolver.resolve(`${typesDir}search.d.ts`)
})
opts.references.push({
path: resolver.resolve(`${typesDir}mutate.d.ts`)
})
})
nuxt.options.imports.dirs?.push('./resources/**')
}
})
nuxt.hook("prepare:types", (opts) => {
const typesDir = "./runtime/types/";
if (!Array.isArray(opts.references)) {
opts.references = [];
}
opts.references.push({
path: resolver.resolve(`${typesDir}restApiSdk.d.ts`),
});
opts.references.push({
path: resolver.resolve(`${typesDir}actions.d.ts`),
});
opts.references.push({
path: resolver.resolve(`${typesDir}search.d.ts`),
});
opts.references.push({
path: resolver.resolve(`${typesDir}mutate.d.ts`),
});
});
},
});