Skip to content

feat: added ability to use the client for sessions and mocking#49

Open
happilymarrieddad wants to merge 1 commit intojensteichert:mainfrom
happilymarrieddad:fix/export-client
Open

feat: added ability to use the client for sessions and mocking#49
happilymarrieddad wants to merge 1 commit intojensteichert:mainfrom
happilymarrieddad:fix/export-client

Conversation

@happilymarrieddad
Copy link

@happilymarrieddad happilymarrieddad commented Feb 20, 2026

Hello, I would like to add the ability to use a session wrapper and I need access to the underlying client. Please accept this pull request so I can get access to it. Also, I would like the ability to add mock testing. Thanks!

  • Nick
package repos

import (
	"context"
	"fmt"

	"github.com/jensteichert/colt"
	"go.mongodb.org/mongo-driver/mongo"
)

// wrapInTransaction handles the boilerplate of starting a session,
// managing the transaction lifecycle, and type-casting the result.
func wrapInTransaction[T any](db *colt.Database, fn func(sCtx mongo.SessionContext) (T, error)) (T, error) {
	var result T

	// Use db.Client() to access the exported Database's Client method
	err := db.Client().UseSession(context.Background(), func(sessionContext mongo.SessionContext) error {

		out, err := sessionContext.WithTransaction(sessionContext, func(sCtx mongo.SessionContext) (interface{}, error) {
			return fn(sCtx)
		})

		if err != nil {
			return err
		}

		if val, ok := out.(T); ok {
			result = val
		}
		return nil
	})

	if err != nil {
		return result, fmt.Errorf("transaction failed: %w", err)
	}

	return result, nil
}

@happilymarrieddad happilymarrieddad changed the title added ability to use the client for sessions and mocking feat: added ability to use the client for sessions and mocking Feb 20, 2026
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

Successfully merging this pull request may close these issues.

1 participant