github.com/oinume/lekcije@v0.0.0-20231017100347-5b4c5eb6ab24/backend/model2/teacher_helper.go (about)

     1  package model2
     2  
     3  import (
     4  	"regexp"
     5  	"strconv"
     6  	"time"
     7  
     8  	"github.com/ericlagergren/decimal"
     9  	"github.com/volatiletech/sqlboiler/v4/types"
    10  
    11  	"github.com/oinume/lekcije/backend/errors"
    12  	"github.com/oinume/lekcije/backend/model"
    13  )
    14  
    15  var (
    16  	idRegexp         = regexp.MustCompile(`^[\d]+$`)
    17  	teacherURLRegexp = regexp.MustCompile(`https?://eikaiwa.dmm.com/teacher/index/([\d]+)`)
    18  )
    19  
    20  func NewTeacher(id uint) *Teacher {
    21  	return &Teacher{ID: id}
    22  }
    23  
    24  func NewTeacherFromIDOrURL(idOrURL string) (*Teacher, error) {
    25  	if idRegexp.MatchString(idOrURL) {
    26  		id, err := strconv.ParseUint(idOrURL, 10, 32)
    27  		if err != nil {
    28  			return nil, err
    29  		}
    30  		return NewTeacher(uint(id)), nil
    31  	} else if group := teacherURLRegexp.FindStringSubmatch(idOrURL); len(group) > 0 {
    32  		id, err := strconv.ParseUint(group[1], 10, 32)
    33  		if err != nil {
    34  			return nil, err
    35  		}
    36  		return NewTeacher(uint(id)), nil
    37  	}
    38  	return nil, errors.NewInvalidArgumentError(
    39  		errors.WithMessage("Failed to parse idOrURL"),
    40  		errors.WithResource(errors.NewResource("teacher", "idOrURL", idOrURL)),
    41  	)
    42  }
    43  
    44  func NewTeacherFromModel(t *model.Teacher) *Teacher {
    45  	birthday := t.Birthday
    46  	if t.Birthday.IsZero() {
    47  		birthday = time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
    48  	}
    49  	rating := decimal.New(0, 2)
    50  	rating.SetFloat64(float64(t.Rating))
    51  	return &Teacher{
    52  		ID:                uint(t.ID),
    53  		Name:              t.Name,
    54  		CountryID:         int16(t.CountryID),
    55  		Gender:            t.Gender,
    56  		Birthday:          birthday,
    57  		YearsOfExperience: int8(t.YearsOfExperience),
    58  		FavoriteCount:     uint(t.FavoriteCount),
    59  		ReviewCount:       uint(t.ReviewCount),
    60  		Rating: types.NullDecimal{
    61  			Big: rating,
    62  		},
    63  		LastLessonAt:    t.LastLessonAt,
    64  		FetchErrorCount: t.FetchErrorCount,
    65  		CreatedAt:       t.CreatedAt,
    66  		UpdatedAt:       t.UpdatedAt,
    67  	}
    68  }