package db import ( "context" "database/sql" "encoding/json" "errors" "fmt" "time" "github.com/hhhapz/hackathon/models" ) func (db *DB) DecodeUser(ctx context.Context, buf []byte) (*models.User, error) { user := &models.User{ Completed: false, CreatedAt: models.NewTime(time.Now()), } if err := json.Unmarshal(buf, &user); err != nil { return nil, fmt.Errorf("could not decode userinfo json: %v", err) } if user.ID == "" { return nil, errors.New("no id found in userinfo") } dbUser, err := models.UserByID(ctx, db.DB, user.ID) switch err { case sql.ErrNoRows: err = user.Insert(ctx, db.DB) if err != nil { return nil, fmt.Errorf("could not create user: %v", err) } dbUser = user fallthrough case nil: return dbUser, nil default: return nil, fmt.Errorf("could not check for user %#v: %v", user, err) } }