Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.1 kB
0
Indexable
Never
// Charges is the resolver for the charges field.
func (r *queryResolver) Charges(ctx context.Context, from string, to string, userID primitive.ObjectID, groupByEntity generated.GroupByEntity, groupByTime generated.GroupByTime) ([]*models.Charge, error) {
	loggedInUserID, isLoggedIn := utils.GetUserId(ctx)
	if !isLoggedIn {
		return nil, fmt.Errorf("not logged in")
	}

	getUserReply, err := r.services.User.GetUser(
		ctx, &pb.GetUserRequest{
			UserID: pointer.String(loggedInUserID.Hex()),
		},
	)
	if err != nil {
		return nil, err
	}

	if getUserReply.User.Id != loggedInUserID.Hex() && !utils.IsAdmin(loggedInUserID) {
		return nil, status.Errorf(codes.PermissionDenied, "not authorized")
	}

	queryChargesReply, err := r.services.Metric.QueryCharges(
		ctx, &pb.QueryChargesRequest{
			UserID:        userID.Hex(),
			StartTime:     from,
			EndTime:       to,
			GroupByEntity: groupByEntity.String(),
			GroupByTime:   groupByTime.String(),
		},
	)
	if err != nil {
		return nil, status.Errorf(
			codes.Internal, "failed to query charges",
		)
	}

	charges := make([]*models.Charge, len(queryChargesReply.Charge))

	return charges, nil
}