Skip to content

Commit

Permalink
feat(next-drupal)!: add public debug() method to DrupalClient
Browse files Browse the repository at this point in the history
Fixes #668

BREAKING CHANGE:
DrupalClient previously had a debug property that indicated if debugging was
enabled. This property has been removed and replaced with a debug() method that
accepts a string and logs it as a debug message if debugging is enabled.
  • Loading branch information
JohnAlbin committed Jan 29, 2024
1 parent 61f723b commit e0fc4bd
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 42 deletions.
75 changes: 38 additions & 37 deletions packages/next-drupal/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ function isClientIdSecretAuth(
export class DrupalClient {
baseUrl: BaseUrl

debug: DrupalClientOptions["debug"]

frontPage: DrupalClientOptions["frontPage"]

private isDebugEnabled: DrupalClientOptions["debug"]

private serializer: DrupalClientOptions["serializer"]

private cache: DrupalClientOptions["cache"]
Expand Down Expand Up @@ -148,7 +148,7 @@ export class DrupalClient {
this.apiPrefix = apiPrefix
this.serializer = serializer
this.frontPage = frontPage
this.debug = debug
this.isDebugEnabled = !!debug
this.useDefaultResourceTypeEntry = useDefaultResourceTypeEntry
this.fetcher = fetcher
this.auth = auth
Expand All @@ -166,7 +166,7 @@ export class DrupalClient {
this.throwJsonApiErrors = false
}

this._debug("Debug mode is on.")
this.debug("Debug mode is on.")
}

set apiPrefix(apiPrefix: DrupalClientOptions["apiPrefix"]) {
Expand Down Expand Up @@ -228,7 +228,7 @@ export class DrupalClient {
// Using the auth set on the client.
// TODO: Abstract this to a re-usable.
if (init?.withAuth) {
this._debug(`Using authenticated request.`)
this.debug(`Using authenticated request.`)

if (init.withAuth === true) {
if (typeof this._auth === "undefined") {
Expand All @@ -240,15 +240,15 @@ export class DrupalClient {
// By default, if withAuth is set to true, we use the auth configured
// in the client constructor.
if (typeof this._auth === "function") {
this._debug(`Using custom auth callback.`)
this.debug(`Using custom auth callback.`)

init["headers"]["Authorization"] = this._auth()
} else if (typeof this._auth === "string") {
this._debug(`Using custom authorization header.`)
this.debug(`Using custom authorization header.`)

init["headers"]["Authorization"] = this._auth
} else if (typeof this._auth === "object") {
this._debug(`Using custom auth credentials.`)
this.debug(`Using custom auth credentials.`)

if (isBasicAuth(this._auth)) {
const basic = Buffer.from(
Expand All @@ -258,7 +258,7 @@ export class DrupalClient {
init["headers"]["Authorization"] = `Basic ${basic}`
} else if (isClientIdSecretAuth(this._auth)) {
// Use the built-in client_credentials grant.
this._debug(`Using default auth (client_credentials).`)
this.debug(`Using default auth (client_credentials).`)

// Fetch an access token and add it to the request.
// Access token can be fetched from cache or using a custom auth method.
Expand All @@ -272,15 +272,15 @@ export class DrupalClient {
}
}
} else if (typeof init.withAuth === "string") {
this._debug(`Using custom authorization header.`)
this.debug(`Using custom authorization header.`)

init["headers"]["Authorization"] = init.withAuth
} else if (typeof init.withAuth === "function") {
this._debug(`Using custom authorization callback.`)
this.debug(`Using custom authorization callback.`)

init["headers"]["Authorization"] = init.withAuth()
} else if (isBasicAuth(init.withAuth)) {
this._debug(`Using basic authorization header`)
this.debug(`Using basic authorization header.`)

const basic = Buffer.from(
`${init.withAuth.username}:${init.withAuth.password}`
Expand All @@ -301,12 +301,12 @@ export class DrupalClient {
}

if (this.fetcher) {
this._debug(`Using custom fetcher.`)
this.debug(`Using custom fetcher, fetching: ${input}`)

return await this.fetcher(input, init)
}

this._debug(`Using default fetch (polyfilled by Next.js).`)
this.debug(`Using default fetch, fetching: ${input}`)

return await fetch(input, init)
}
Expand All @@ -329,8 +329,7 @@ export class DrupalClient {

const url = this.buildUrl(apiPath, options?.params)

this._debug(`Creating resource of type ${type}.`)
this._debug(url.toString())
this.debug(`Creating resource of type ${type}.`)

// Add type to body.
body.data.type = type
Expand Down Expand Up @@ -373,8 +372,7 @@ export class DrupalClient {
options?.params
)

this._debug(`Creating file resource for media of type ${type}.`)
this._debug(url.toString())
this.debug(`Creating file resource for media of type ${type}.`)

const response = await this.fetch(url.toString(), {
method: "POST",
Expand Down Expand Up @@ -415,8 +413,7 @@ export class DrupalClient {

const url = this.buildUrl(`${apiPath}/${uuid}`, options?.params)

this._debug(`Updating resource of type ${type} with id ${uuid}.`)
this._debug(url.toString())
this.debug(`Updating resource of type ${type} with id ${uuid}.`)

// Update body.
body.data.type = type
Expand Down Expand Up @@ -455,8 +452,7 @@ export class DrupalClient {

const url = this.buildUrl(`${apiPath}/${uuid}`, options?.params)

this._debug(`Deleting resource of type ${type} with id ${uuid}.`)
this._debug(url.toString())
this.debug(`Deleting resource of type ${type} with id ${uuid}.`)

const response = await this.fetch(url.toString(), {
method: "DELETE",
Expand Down Expand Up @@ -489,7 +485,7 @@ export class DrupalClient {
const cached = (await this.cache.get(options.cacheKey)) as string

if (cached) {
this._debug(`Returning cached resource ${type} with id ${uuid}`)
this.debug(`Returning cached resource ${type} with id ${uuid}.`)

const json = JSON.parse(cached)

Expand All @@ -504,8 +500,7 @@ export class DrupalClient {

const url = this.buildUrl(`${apiPath}/${uuid}`, options?.params)

this._debug(`Fetching resource ${type} with id ${uuid}.`)
this._debug(url.toString())
this.debug(`Fetching resource ${type} with id ${uuid}.`)

const response = await this.fetch(url.toString(), {
withAuth: options.withAuth,
Expand Down Expand Up @@ -687,6 +682,8 @@ export class DrupalClient {
_format: "json",
})

this.debug(`Fetching resource by path, ${path}.`)

const response = await this.fetch(url.toString(), {
method: "POST",
credentials: "include",
Expand Down Expand Up @@ -739,8 +736,7 @@ export class DrupalClient {
...options?.params,
})

this._debug(`Fetching resource collection of type ${type}`)
this._debug(url.toString())
this.debug(`Fetching resource collection of type ${type}.`)

const response = await this.fetch(url.toString(), {
withAuth: options.withAuth,
Expand Down Expand Up @@ -910,6 +906,8 @@ export class DrupalClient {
path,
})

this.debug(`Fetching translated path, ${path}.`)

const response = await this.fetch(url.toString(), {
withAuth: options.withAuth,
})
Expand Down Expand Up @@ -990,6 +988,8 @@ export class DrupalClient {
)

try {
this.debug(`Fetching JSON:API index.`)

const response = await this.fetch(url.toString(), {
// As per https://www.drupal.org/node/2984034 /jsonapi is public.
withAuth: false,
Expand Down Expand Up @@ -1123,7 +1123,7 @@ export class DrupalClient {
const cached = (await this.cache.get(options.cacheKey)) as string

if (cached) {
this._debug(`Returning cached menu items for ${name}`)
this.debug(`Returning cached menu items for ${name}.`)
return JSON.parse(cached)
}
}
Expand All @@ -1138,8 +1138,7 @@ export class DrupalClient {
options.params
)

this._debug(`Fetching menu items for ${name}.`)
this._debug(url.toString())
this.debug(`Fetching menu items for ${name}.`)

const response = await this.fetch(url.toString(), {
withAuth: options.withAuth,
Expand Down Expand Up @@ -1212,6 +1211,8 @@ export class DrupalClient {
options.params
)

this.debug(`Fetching view, ${viewId}.${displayId}.`)

const response = await this.fetch(url.toString(), {
withAuth: options.withAuth,
})
Expand Down Expand Up @@ -1252,6 +1253,8 @@ export class DrupalClient {
options.params
)

this.debug(`Fetching search index, ${name}.`)

const response = await this.fetch(url.toString(), {
withAuth: options.withAuth,
})
Expand Down Expand Up @@ -1330,11 +1333,11 @@ export class DrupalClient {
this._token &&
Date.now() < this.tokenExpiresOn
) {
this._debug(`Using existing access token.`)
this.debug(`Using existing access token.`)
return this._token
}

this._debug(`Fetching new access token.`)
this.debug(`Fetching new access token.`)

const basic = Buffer.from(`${clientId}:${clientSecret}`).toString("base64")

Expand All @@ -1343,7 +1346,7 @@ export class DrupalClient {
if (opts?.scope) {
body = `${body}&scope=${opts.scope}`

this._debug(`Using scope: ${opts.scope}`)
this.debug(`Using scope: ${opts.scope}`)
}

const response = await this.fetch(url.toString(), {
Expand All @@ -1362,8 +1365,6 @@ export class DrupalClient {

const result: AccessToken = await response.json()

this._debug(result)

this.token = result

this.accessTokenScope = opts?.scope
Expand Down Expand Up @@ -1411,8 +1412,8 @@ export class DrupalClient {
return message
}

private _debug(message) {
!!this.debug && this.logger.debug(message)
debug(message) {
this.isDebugEnabled && this.logger.debug(message)
}

// Error handling.
Expand Down
13 changes: 9 additions & 4 deletions packages/next-drupal/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import type { Logger } from "./types"

export const LOG_MESSAGE_PREFIX = "[next-drupal][log]:"
export const DEBUG_MESSAGE_PREFIX = "[next-drupal][debug]:"
export const WARN_MESSAGE_PREFIX = "[next-drupal][warn]:"
export const ERROR_MESSAGE_PREFIX = "[next-drupal][error]:"

// Default logger. Uses console.
export const logger: Logger = {
log(message) {
console.log(`[next-drupal][log]:`, message)
console.log(LOG_MESSAGE_PREFIX, message)
},
debug(message) {
console.debug(`[next-drupal][debug]:`, message)
console.debug(DEBUG_MESSAGE_PREFIX, message)
},
warn(message) {
console.warn(`[next-drupal][debug]:`, message)
console.warn(WARN_MESSAGE_PREFIX, message)
},
error(message) {
console.error(`[next-drupal][error]:`, message)
console.error(ERROR_MESSAGE_PREFIX, message)
},
}
2 changes: 1 addition & 1 deletion packages/next-drupal/tests/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ describe("DrupalClient", () => {
"[next-drupal][debug]:",
"Debug mode is on."
)
expect(client.debug).toBe(true)
expect(client.isDebugEnabled).toBe(true)
})
})

Expand Down

0 comments on commit e0fc4bd

Please sign in to comment.