Content-Length: 484806 | pFad | http://github.com/nextauthjs/next-auth/pull/11911/commits/14efdfe7c368e590eeb117973ee44475bffe6347

54 fix(adapter): transistion to surrealdb@^1.0.0 by dvanmali · Pull Request #11911 · nextauthjs/next-auth · GitHub
Skip to content

fix(adapter): transistion to surrealdb@^1.0.0 #11911

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 31 commits into from
Jun 8, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
ccefb64
feat: transition from surrealdb.js beta to surrealdb@1.0.0
dvanmali Sep 26, 2024
b0a7bf9
fix: ensure correct adapter type is returned with verified is nulled …
dvanmali Sep 26, 2024
fd4690b
merge: fix conflicts from conflicts
dvanmali Sep 26, 2024
9756ad1
fix: remove log print on test
dvanmali Oct 2, 2024
14efdfe
feat: more AnyAuth login variables, support HTTP rpc connection, add …
dvanmali Oct 2, 2024
395f827
merge: with upstream/main
dvanmali Oct 2, 2024
1ee3a30
Merge branch 'main' of github.com:nextauthjs/next-auth
dvanmali Oct 2, 2024
d3aabc9
restore: changes
dvanmali Oct 2, 2024
34ebb2c
restore: changes
dvanmali Oct 2, 2024
bd1116b
doc: add all env variables available
dvanmali Oct 2, 2024
bc6b85c
fix: throw error not string
dvanmali Oct 2, 2024
36a9f2d
merge: upstream main
dvanmali Oct 9, 2024
c1af8dc
Merge branch 'main' into main
dvanmali Oct 25, 2024
102c8f0
Merge branch 'main' into main
dvanmali Nov 8, 2024
f15a43a
Merge branch 'main' into main
dvanmali Jan 14, 2025
1885d62
Merge branch 'main' into main
dvanmali Feb 10, 2025
59df6a3
Merge branch 'main' into main
dvanmali Mar 14, 2025
c5d2b61
Merge branch 'main' into main
ThangHuuVu May 10, 2025
5aade68
Merge branch 'main' into main
ThangHuuVu May 10, 2025
7c19313
merge: upstream
dvanmali May 12, 2025
89f9467
fix: uses surrealdb:^v1.3.0 for native reconnectivity, feat: add weba…
dvanmali May 13, 2025
293c64b
fix: creating user should use id() not randomUUID()
dvanmali May 13, 2025
fe650dd
fix: ignored files from prettier
dvanmali May 13, 2025
12c90ab
chore: upgrade lockfile as requested
dvanmali May 13, 2025
f7935b4
Merge branch 'main' into main
dvanmali May 13, 2025
5845c1f
Merge branch 'main' of github.com:nextauthjs/next-auth
dvanmali May 19, 2025
e0786c9
fix: tsc build errors
dvanmali May 19, 2025
7c27a9f
Merge branch 'main' of github.com:dvanmali/next-auth
dvanmali May 19, 2025
241426c
fix: tsc build errors
dvanmali May 19, 2025
c000302
Merge branch 'main' into main
dvanmali May 27, 2025
f27fa22
Merge branch 'main' into main
ndom91 Jun 3, 2025
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
Prev Previous commit
Next Next commit
feat: more AnyAuth login variables, support HTTP rpc connection, add …
…exponential backoff for disconnection events to example
  • Loading branch information
dvanmali committed Oct 2, 2024
commit 14efdfe7c368e590eeb117973ee44475bffe6347
177 changes: 163 additions & 14 deletions docs/pages/getting-started/adapters/surrealdb.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -97,37 +97,186 @@ app.use(

The SurrealDB adapter does not handle connections automatically, so you will have to make sure that you pass the Adapter a `SurrealDBClient` that is connected already. Below you can see an example how to do this.

### Authorization
### Utils File

```ts filename="./lib/surrealdb_utils.ts"
import { Surreal, ConnectionStatus, type AnyAuth } from "surrealdb"

/**
* Maintains a single instance of surrealdb
*/
export class MySurreal {
// A single instantiation of a surreal connection
private _surrealdb: Surreal | undefined

async surrealdb(url: string | URL, auth: AnyAuth | string): Promise<Surreal> {
// Init Surreal
if (!this._surrealdb) {
this._surrealdb = new Surreal()
}

if (this._surrealdb.status == ConnectionStatus.Connected) {
return this._surrealdb
} else if (this._surrealdb.status == ConnectionStatus.Disconnected) {
try {
// Connect as a database user
await this._surrealdb.connect(url, {
auth,
})
if (process.env.NODE_ENV === "development") {
let str = `${this._surrealdb.status}`
if (typeof auth !== "string") {
if ("username" in auth) str += ` as ${auth.username}`
if ("database" in auth && "namespace" in auth)
str += ` for ${auth.namespace} ${auth.database}`
else if ("namespace" in auth) str += ` for ${auth.namespace}`
else if ("database" in auth) str += ` for ${auth.database}`
}
console.info(str)
}
} catch (error) {
if (error instanceof Error) throw error
throw new Error(error as unknown as string)
}
}
return this._surrealdb
}
}

export const surrealdb = new MySurreal()

/**
* Converts environment variables to an AnyAuth type
* to connect with the database
* @param param0 - environment variables
* @returns {RootAuth | NamespaceAuth | DatabaseAuth | ScopeAuth}
*/
export function toAnyAuth({
username,
password,
namespace,
database,
scope,
}: Record<string, string | undefined>) {
let auth: AnyAuth
if (username && password && namespace && database) {
auth = {
database,
namespace,
username,
password,
}
} else if (username && password && namespace) {
auth = {
namespace,
username,
password,
}
} else if (username && password) {
auth = {
username,
password,
}
} else if (scope) {
auth = {
namespace,
database,
username,
password,
scope,
}
} else {
throw new Error("unsupported any auth configuration")
}
return auth
}

#### Websocket Method:
/**
* Handles a disconnection with the database with exponential backoff
* @param surreal - the single instance of surreal
* @param url - the database url
* @param auth - auth credentials
* @param {number} [reconnectDelay = 1000] - initial delay amount
* @param {number} [max_retries = 5] - maximum number of retries
* @param {number} [retry = 0] - current retry
*/
export async function handleDisconnect(
surreal: MySurreal,
url: string | URL,
auth: AnyAuth,
reconnectDelay: number = 1000,
max_retries: number = 5,
retry: number = 0
) {
if (retry >= max_retries) {
console.error("Shutting down.")
process.exit(1) // Graceful exit or handle gracefully in a production environment.
}

With this configuration, we can use the websocket endpoint. Thus, the `AUTH_SURREAL_URL` should begin with `ws` or `wss`.
retry++
console.log(`Reconnect in ${reconnectDelay}ms...`)
setTimeout(async () => {
try {
await surreal.surrealdb(url, auth)
console.log("reconnected")
} catch (err) {
console.error("Reconnection attempt failed")
handleDisconnect(
surreal,
url,
auth,
retry,
max_retries,
reconnectDelay * 2
) // Recursively try to reconnect.
}
}, reconnectDelay)
}
```

### Authorization

The clientPromise provides a connection to the database.

```ts filename="./lib/surrealdb.ts"
import { Surreal } from "surrealdb"
import { type Surreal } from "surrealdb"
import { surrealdb, toAnyAuth } from "../lib/surrealdb"
import { handleDisconnect, MySurreal, toAnyAuth } from "./lib/surrealdb_utils"

const clientPromise = new Promise<Surreal>(async (resolve, reject) => {
try {
const db = new Surreal()
const {
AUTH_SURREAL_URL: url,
AUTH_SURREAL_NS: namespace,
AUTH_SURREAL_DB: database,
AUTH_SURREAL_USER: username,
AUTH_SURREAL_PW: password,
AUTH_SURREAL_SCOPE: scope,
} = process.env
if (url && namespace && database && username && password) {
await db.connect(url)
await db.signin({
namespace,
database,
username,
password,
})
}
if (!url) throw "required auth url"
const auth = toAnyAuth({
namespace,
database,
username,
password,
scope,
})
const surreal = new MySurreal()
const db = await surreal.surrealdb(url, auth)
db.emitter.subscribe("disconnected", async () => {
handleDisconnect(surreal, url, auth)
})
resolve(db)
} catch (e) {
reject(e)
}
})
```

#### HTTP ENGINE

With this configuration, we can use the database's http endpoint. Thus, the `AUTH_SURREAL_URL` should begin with `http` or `https`.

#### Websocket ENGINE

With this configuration, we can use the database's websocket endpoint. Thus, the `AUTH_SURREAL_URL` should begin with `ws` or `wss`.
2 changes: 1 addition & 1 deletion packages/adapter-surrealdb/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export const sessionToDoc = (
})

/** @internal */
// Convert AdapterAccount to DB object
// Convert VerificationToken to DB object
const verificationTokenToDoc = (
account: VerificationToken
): Omit<VerificationTokenDoc, "id"> => ({
Expand Down
13 changes: 7 additions & 6 deletions packages/adapter-surrealdb/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ const clientPromise = new Promise<Surreal>(async (resolve, reject) => {
const db = new Surreal()
try {
const db = new Surreal()
await db.connect("ws://0.0.0.0:8000")
await db.signin({
namespace: "test",
database: "test",
username: "test",
password: "test",
await db.connect("ws://0.0.0.0:8000", {
auth: {
namespace: "test",
database: "test",
username: "test",
password: "test",
},
})
resolve(db)
} catch (e) {
Expand Down
Loading








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/nextauthjs/next-auth/pull/11911/commits/14efdfe7c368e590eeb117973ee44475bffe6347

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy