Skip to content

Commit

Permalink
Refactor configAIAssistant to allow config overrides
Browse files Browse the repository at this point in the history
  • Loading branch information
pamella committed Jun 19, 2024
1 parent 0dd9beb commit 1943544
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 13 deletions.
2 changes: 1 addition & 1 deletion example/assets/js/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const theme = createTheme({});

// Relates to path("ai-assistant/", include("django_ai_assistant.urls"))
// which can be found at example/demo/urls.py)
configAIAssistant({ baseURL: "ai-assistant" });
configAIAssistant({ BASE: "ai-assistant" });

const ExampleIndex = () => {
return (
Expand Down
35 changes: 23 additions & 12 deletions frontend/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,38 @@
import cookie from "cookie";

import { OpenAPI } from "./client";
import { OpenAPI, OpenAPIConfig } from "./client";
import { AxiosRequestConfig } from "axios";

/**
* Configures the base URL for the AI Assistant API which is path associated with
* the Django include.
* Configures the AI Assistant client, such as setting the base URL (which is
* associated with the Django path include) and request interceptors.
*
* Configures the Axios request to include the CSRF token if it exists.
* By default, this function will add a request interceptor to include the CSRF token
* in the request headers if it exists. You can override the default request interceptor
* by providing your own request interceptor function in the configuration object.
*
* @param baseURL Base URL of the AI Assistant API.
* NOTE: This function must be called in the root of your application before any
* requests are made to the AI Assistant API.
*
* @param props An `OpenAPIConfig` object containing configuration options for the OpenAPI client.
*
* @example
* configAIAssistant({ baseURL: "ai-assistant" });
* configAIAssistant({ BASE: "ai-assistant" });
*/
export function configAIAssistant({ baseURL }: { baseURL: string }) {
OpenAPI.BASE = baseURL;

OpenAPI.interceptors.request.use((request: AxiosRequestConfig) => {
export function configAIAssistant(props: OpenAPIConfig): OpenAPIConfig {
function defaultRequestInterceptor(request: AxiosRequestConfig) {
const { csrftoken } = cookie.parse(document.cookie);
if (request.headers && csrftoken) {
if (csrftoken && request.headers) {
request.headers["X-CSRFTOKEN"] = csrftoken;
}
return request;
});
}

OpenAPI.interceptors.request.use(defaultRequestInterceptor);

// Apply the configuration options to the OpenAPI client, and allow the user
// to override the default request interceptor.
Object.assign(OpenAPI, props);

return OpenAPI;
}

0 comments on commit 1943544

Please sign in to comment.