59 lines
1.9 KiB
Go
59 lines
1.9 KiB
Go
package http
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"primaya-api/cpone-middleware/internal/repository"
|
|
)
|
|
|
|
var validLabNumber = regexp.MustCompile(`^[A-Za-z0-9-]+$`)
|
|
|
|
type LabResultResponse struct {
|
|
Success bool `json:"success"`
|
|
Status string `json:"status"`
|
|
Message string `json:"message"`
|
|
Data *repository.LabResultData `json:"data"`
|
|
}
|
|
|
|
func (h Handler) GetLabResult(w http.ResponseWriter, r *http.Request) {
|
|
labNumber := strings.TrimSpace(r.PathValue("labNumber"))
|
|
if labNumber == "" {
|
|
writeLabResultResponse(w, http.StatusUnprocessableEntity, false, "validation_error", "Nomor laboratorium wajib diisi", nil)
|
|
return
|
|
}
|
|
if utf8.RuneCountInString(labNumber) > 50 {
|
|
writeLabResultResponse(w, http.StatusUnprocessableEntity, false, "validation_error", "Nomor laboratorium maksimal 50 karakter", nil)
|
|
return
|
|
}
|
|
if !validLabNumber.MatchString(labNumber) {
|
|
writeLabResultResponse(w, http.StatusUnprocessableEntity, false, "validation_error", "Nomor laboratorium hanya boleh berisi huruf, angka, dan tanda hubung", nil)
|
|
return
|
|
}
|
|
|
|
outcome, err := h.labResultRepository(r.Context()).GetLabResult(r.Context(), strings.ToUpper(labNumber))
|
|
if err != nil {
|
|
var validationErr repository.ValidationError
|
|
if errors.As(err, &validationErr) {
|
|
writeLabResultResponse(w, http.StatusUnprocessableEntity, false, "validation_error", validationErr.Message, nil)
|
|
return
|
|
}
|
|
writeLabResultResponse(w, http.StatusInternalServerError, false, "error", err.Error(), nil)
|
|
return
|
|
}
|
|
|
|
writeLabResultResponse(w, outcome.HTTPStatus, outcome.Success, outcome.Status, outcome.Message, outcome.Data)
|
|
}
|
|
|
|
func writeLabResultResponse(w http.ResponseWriter, statusCode int, success bool, status, message string, data *repository.LabResultData) {
|
|
WriteJSON(w, statusCode, LabResultResponse{
|
|
Success: success,
|
|
Status: status,
|
|
Message: message,
|
|
Data: data,
|
|
})
|
|
}
|