Casting a vote
Before our API is a complete feature, we need to add the ability for users to cast votes. We'll break this piece into two functions in order to increase the readability of our code.
Inside votes.go
, add the following function:
func CastVote(ctx context.Context, answerKey *datastore.Key, score int) (*Vote, error) { question, err := GetQuestion(ctx, answerKey.Parent()) if err != nil { return nil, err } user, err := UserFromAEUser(ctx) if err != nil { return nil, err } var vote Vote err = datastore.RunInTransaction(ctx, func(ctx context.Context) error { var err error vote, err = castVoteInTransaction(ctx, answerKey, question, user, score) if err != nil { return err } return nil }, &datastore.TransactionOptions{XG: true}) if err != nil { return nil, err } return &vote, nil }
The CastVote
function takes (along with the obligatory Context
) datastore.Key
for the answer that is being voted...