|
| 1 | +package routes |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + |
| 7 | + "github.com/f1monkey/spellchecker-web/internal/spellchecker" |
| 8 | + "github.com/swaggest/usecase" |
| 9 | + "github.com/swaggest/usecase/status" |
| 10 | +) |
| 11 | + |
| 12 | +type DictionaryItemAddRequest struct { |
| 13 | + Code string `path:"code" minLength:"1"` |
| 14 | + |
| 15 | + Phrases []DictionaryItemPhrase `json:"phrases" minLength:"1"` |
| 16 | +} |
| 17 | + |
| 18 | +type DictionaryItemPhrase struct { |
| 19 | + Text string `json:"text" description:"The word or phrase to be added to the dictionary."` |
| 20 | + Weight uint `json:"weight" min:"1" description:"A numeric value indicating the importance or influence of this entry in spellchecking or suggestions."` |
| 21 | +} |
| 22 | + |
| 23 | +type DictionaryItemAddResponse struct { |
| 24 | + Words int `json:"words" description:"Number of phrases successfully added."` |
| 25 | +} |
| 26 | + |
| 27 | +func dictionaryItemAdd(registry *spellchecker.Registry) usecase.Interactor { |
| 28 | + u := usecase.NewInteractor(func(ctx context.Context, input DictionaryItemAddRequest, output *DictionaryItemAddResponse) error { |
| 29 | + sc, err := registry.Get(input.Code) |
| 30 | + if errors.Is(spellchecker.ErrNotFound, err) { |
| 31 | + return status.Wrap(err, status.NotFound) |
| 32 | + } else if err != nil { |
| 33 | + return status.Wrap(err, status.Internal) |
| 34 | + } |
| 35 | + |
| 36 | + wordCnt := 0 |
| 37 | + |
| 38 | + for i := range input.Phrases { |
| 39 | + |
| 40 | + words := wordSymbols.FindAllString(input.Phrases[i].Text, -1) |
| 41 | + if len(words) == 0 { |
| 42 | + continue |
| 43 | + } |
| 44 | + |
| 45 | + weight := input.Phrases[i].Weight |
| 46 | + if weight == 0 { |
| 47 | + weight = 1 |
| 48 | + } |
| 49 | + |
| 50 | + sc.AddWeight(weight, words...) |
| 51 | + wordCnt += len(words) |
| 52 | + } |
| 53 | + |
| 54 | + output.Words = wordCnt |
| 55 | + |
| 56 | + return nil |
| 57 | + }) |
| 58 | + |
| 59 | + u.SetTitle("Add phrases/words to spellchecker") |
| 60 | + u.SetDescription("Adds one or more custom phrases or words to the spellchecker dictionary. Each phrase can have an optional weight to influence matching or prioritization.") |
| 61 | + u.SetExpectedErrors(status.Internal) |
| 62 | + |
| 63 | + return u |
| 64 | +} |
0 commit comments