NestJS CRUD
Refine provides a data provider for APIs powered with Nest.js CRUD, a module for Nest.js that provides easier ways to build CRUD RESTful APIs.
Good to know:
- This library uses
axios
to handle the requests. - To learn more about data fetching in Refine, check out the Data Fetching guide.
Installation
- npm
- pnpm
- yarn
npm i @refinedev/nestjsx-crud
pnpm add @refinedev/nestjsx-crud
yarn add @refinedev/nestjsx-crud
Usage
We'll provide the API url to the dataProvider
function to create a data provider.
app.tsx
import Refine from "@refinedev/core";
import dataProvider from "@refinedev/nestjsx-crud";
const App = () => (
<Refine
dataProvider={dataProvider("<API_URL>")}
>
{/* ... */}
</Refine>
);
Authentication
If your API uses authentication, you can easily provide an axios instance with the authentication headers to the dataProvider
function via second argument.
- Using Headers
- Using Interceptors
App.tsx
import { Refine, AuthProvider } from "@refinedev/core";
/**
* We're using the `axiosInstance` exported from the package
* But you are free to use your own instance with your own configuration.
*/
import dataProvider, { axiosInstance } from "@refinedev/nestjsx-crud";
const authProvider: AuthProvider = {
login: async () => {
// ...
// We're setting the Authorization header when the user logs in.
axiosInstance.defaults.headers.common[
"Authorization"
] = `Bearer ${localStorage.getItem("token")}`;
},
logout: async () => {
// ...
// We're removing the Authorization header when the user logs out.
axiosInstance.defaults.headers.common["Authorization"] = undefined;
},
// ...
};
const App = () => {
return (
<Refine
dataProvider={dataProvider("<API_URL>", axiosInstance)}
authProvider={authProvider}
>
{/* ... */}
</Refine>
);
};
App.tsx
import { Refine, AuthProvider } from "@refinedev/core";
/**
* We're using the `axiosInstance` exported from the package
* But you are free to use your own instance with your own configuration.
*/
import dataProvider, { axiosInstance } from "@refinedev/nestjsx-crud";
axiosInstance.interceptors.request.use(
(config) => {
// ...
// We're setting the Authorization header if it's available in the localStorage.
const token = localStorage.getItem("token");
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
},
);
const App = () => {
return (
<Refine
dataProvider={dataProvider("<API_URL>", axiosInstance)}
>
{/* ... */}
</Refine>
);
};
Example
Run on your local
npm create refine-app@latest -- --example data-provider-nestjsx-crud