github.com/ngocphuongnb/tetua@v0.0.7-alpha/packages/entrepository/topic.go (about) 1 package entrepository 2 3 import ( 4 "context" 5 "fmt" 6 7 e "github.com/ngocphuongnb/tetua/app/entities" 8 "github.com/ngocphuongnb/tetua/packages/entrepository/ent" 9 "github.com/ngocphuongnb/tetua/packages/entrepository/ent/topic" 10 ) 11 12 type TopicRepository struct { 13 *BaseRepository[e.Topic, ent.Topic, *ent.TopicQuery, *e.TopicFilter] 14 } 15 16 func (c *TopicRepository) ByName(ctx context.Context, name string) (*e.Topic, error) { 17 t, err := c.Client.Topic.Query().Where(topic.NameEQ(name)).Only(ctx) 18 if err != nil { 19 return nil, EntError(err, fmt.Sprintf("topic not found with name: %s", name)) 20 } 21 return entTopicToTopic(t), err 22 } 23 24 func CreateTopicRepository(client *ent.Client) *TopicRepository { 25 return &TopicRepository{ 26 BaseRepository: &BaseRepository[e.Topic, ent.Topic, *ent.TopicQuery, *e.TopicFilter]{ 27 Name: "topic", 28 Client: client, 29 ConvertFn: entTopicToTopic, 30 ByIDFn: func(ctx context.Context, client *ent.Client, id int) (*ent.Topic, error) { 31 return client.Topic.Query().Where(topic.IDEQ(id)).Only(ctx) 32 }, 33 DeleteByIDFn: func(ctx context.Context, client *ent.Client, id int) error { 34 return client.Topic.DeleteOneID(id).Exec(ctx) 35 }, 36 CreateFn: func(ctx context.Context, client *ent.Client, data *e.Topic) (topic *ent.Topic, err error) { 37 tc := client.Topic.Create(). 38 SetName(data.Name). 39 SetSlug(data.Slug). 40 SetDescription(data.Description). 41 SetContent(data.Content). 42 SetContentHTML(data.ContentHTML) 43 if data.ParentID != 0 { 44 tc = tc.SetParentID(data.ParentID) 45 } 46 return tc.Save(ctx) 47 }, 48 UpdateFn: func(ctx context.Context, client *ent.Client, data *e.Topic) (topic *ent.Topic, err error) { 49 tc := client.Topic.UpdateOneID(data.ID). 50 SetName(data.Name). 51 SetSlug(data.Slug). 52 SetDescription(data.Description). 53 SetContent(data.Content). 54 SetContentHTML(data.ContentHTML) 55 if data.ParentID != 0 { 56 tc = tc.SetParentID(data.ParentID) 57 } 58 return tc.Save(ctx) 59 }, 60 QueryFilterFn: func(client *ent.Client, filters ...*e.TopicFilter) *ent.TopicQuery { 61 query := client.Topic.Query().Where(topic.DeletedAtIsNil()) 62 if len(filters) > 0 && filters[0].Search != "" { 63 query = query.Where(topic.NameContainsFold(filters[0].Search)) 64 } 65 return query 66 }, 67 FindFn: func(ctx context.Context, query *ent.TopicQuery, filters ...*e.TopicFilter) ([]*ent.Topic, error) { 68 page, limit, sorts := getPaginateParams(filters...) 69 return query. 70 Limit(limit). 71 Offset((page - 1) * limit). 72 Order(sorts...). 73 All(ctx) 74 }, 75 }, 76 } 77 }