graphqlidentity.go

 1// Package graphqlidentity contains helpers for managing identities within the GraphQL API.
 2package graphqlidentity
 3
 4import (
 5	"context"
 6
 7	"github.com/MichaelMure/git-bug/cache"
 8	"github.com/MichaelMure/git-bug/entity"
 9	"github.com/MichaelMure/git-bug/identity"
10	"github.com/MichaelMure/git-bug/repository"
11)
12
13// identityCtxKey is a unique context key, accessible only in this package.
14var identityCtxKey = &struct{}{}
15
16// AttachToContext attaches an Identity to a context.
17func AttachToContext(ctx context.Context, u *identity.Identity) context.Context {
18	return context.WithValue(ctx, identityCtxKey, u.Id())
19}
20
21// ForContext retrieves an IdentityCache from the context, or nil if no identity is present.
22// If an error occurs while resolving the identity (e.g. I/O error), then it will be returned.
23func ForContext(ctx context.Context, r *cache.RepoCache) (*cache.IdentityCache, error) {
24	id, ok := ctx.Value(identityCtxKey).(entity.Id)
25	if !ok {
26		return nil, nil
27	}
28	return r.ResolveIdentity(id)
29}
30
31// ForContextUncached retrieves an Identity from the context, or nil if no identity is present.
32// If an error occurs while resolving the identity (e.g. I/O error), then it will be returned.
33func ForContextUncached(ctx context.Context, repo repository.Repo) (*identity.Identity, error) {
34	id, ok := ctx.Value(identityCtxKey).(entity.Id)
35	if !ok {
36		return nil, nil
37	}
38	return identity.ReadLocal(repo, id)
39}