Skip to content
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

Provide a way to use custom client #1

Open
ArtemSBulgakov opened this issue Jun 14, 2024 · 1 comment
Open

Provide a way to use custom client #1

ArtemSBulgakov opened this issue Jun 14, 2024 · 1 comment

Comments

@ArtemSBulgakov
Copy link

Hello.

I use different method to make requests (axios instead of fetch). Also, I've implemented custom logic to receive tokens, it should be run before each request. But the current implementation of library doesn't let me to integrate my methods into client.

It would be cool if we could write a custom request method and provide to initializeClient.

One possible way is to just export createClientProxy function, so we could just implement some MoodleClient interface without touching Proxy logic.

@ArtemSBulgakov
Copy link
Author

Found a way to redefine request method:

import { initializeClient } from "moodle-typed-ws"
import { serialize } from "object-to-formdata"
import { wsQueryPromise } from "./api.ts"
import { MOODLE_URL, MOODLE_WS_URL } from "./config.ts"

type MoodleFunction = (arg: object) => Promise<unknown>

export const MoodleClient = initializeClient({
  baseUrl: MOODLE_URL,
  token: "",
})
MoodleClient.utils.request = async <F extends MoodleFunction>(functionName: string, params: Parameters<F>[0]) => {
  return wsQueryPromise<ReturnType<F>>({
    url: MOODLE_WS_URL,
    data: {
      moodlewsrestformat: "json",
      wsfunction: functionName,
      ...serializeForm(params),
    },
  })
}

export const serializeForm = (data: unknown) => {
  return Object.fromEntries([
    ...serialize(data, {
      indices: true,
      booleansAsIntegers: true, // Moodle doesn't understand booleans
    }).entries(),
  ])
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant