-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Inject gorm.DB in the context using the context/database package
- Loading branch information
Edoardo Rossi
committed
Sep 10, 2020
1 parent
2984490
commit 66ef7ba
Showing
3 changed files
with
46 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package database | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/jinzhu/gorm" | ||
) | ||
|
||
type ctxDatabaseMarker struct{} | ||
|
||
type ctxDatabase struct { | ||
database *gorm.DB | ||
} | ||
|
||
var ( | ||
ctxDatabaseKey = &ctxDatabaseMarker{} | ||
) | ||
|
||
// Extract takes the gorm.DB database from the context. | ||
// If the ctxDatabase wasn't used, an error is returned. | ||
func Extract(ctx context.Context) (*gorm.DB, error) { | ||
d, ok := ctx.Value(ctxDatabaseKey).(*ctxDatabase) | ||
if !ok || d == nil { | ||
return nil, fmt.Errorf("Unable to get the database") | ||
} | ||
|
||
return d.database, nil | ||
} | ||
|
||
// ToContext adds the gorm.DB database to the context for extraction later. | ||
// Returning the new context that has been created. | ||
func ToContext(ctx context.Context, db *gorm.DB) context.Context { | ||
d := &ctxDatabase{ | ||
database: db, | ||
} | ||
return context.WithValue(ctx, ctxDatabaseKey, d) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters