credo-ts icon indicating copy to clipboard operation
credo-ts copied to clipboard

Update to new `using` syntax so we don't have to use a callback for `withSession`

Open sairanjit opened this issue 11 months ago • 0 comments

This change simplifies session management by automatically handling cleanup with Symbol.asyncDispose https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management

Before

public async withSession<Return>(callback: (session: Session) => Return): Promise<Awaited<Return>> {
    let session: Session | undefined = undefined
    try {
      session = await this.store.session(this.profile).open()

      const result = await callback(session)

      return result
    } finally {
      if (session?.handle) {
        await session.close()
      }
    }
  }

After

public async getSession() {
    const session = await this.store.session(this.profile).open()
    return {
      session,
      [Symbol.asyncDispose]: async () => {
        if (session?.handle) {
          await session.close()
        }
      },
    }
  }

And usage of the session will also be changed from Before

await agentContext.wallet.withSession((session) =>
  session.insert({ category: record.type, name: record.id, value, tags })
)

After

await using session = await agentContext.wallet.getSession()

await session.session.insert({ category: record.type, name: record.id, value, tags })

Some initial changes that are required to start using the using keyword are :

  • [ ] Update prettier to v3 and also dependent packages
  • [ ] Update tsconfig with "lib": ["ESNext.Disposable"]

@TimoGlastra Do you think any more changes are required or this would be a good start ?

sairanjit avatar Jan 07 '25 15:01 sairanjit