diff --git a/api/openapi/openapi.yml b/api/openapi/openapi.yml index 54a5fb2..ce00ebd 100644 --- a/api/openapi/openapi.yml +++ b/api/openapi/openapi.yml @@ -1,15 +1,19 @@ openapi: '3.0.2' info: title: 42Activity API - description: "アクティビティを管理するAPIです" version: '1.0' servers: - url: http://localhost:4242 paths: /shifts: get: + tags: + - シフト管理 summary: "シフトの取得" - description: "特定の日付のシフトを担当するUserの配列を返します" + description: | + ## 概要 + 指定した日付のシフトを担当するUserの配列を返却する + 指定した日付にシフトが存在しない場合は空の配列を返却する parameters: - name: date in: query @@ -18,76 +22,118 @@ paths: schema: {type: string, example: "2024-05-01"} responses: '200': - description: "成功。Userの配列をjsonで返します" + description: "" content: application/json: schema: - $ref: '#/components/schemas/shiftsArray' + $ref: './openapi.yml#/components/schemas/shiftsArray' '400': - description: "失敗。エラーメッセージをjsonで返します" + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error400' + '500': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error500' post: + tags: + - シフト管理 summary: "シフトの追加" - description: "日付とそれに対応した複数loginをDBに反映する" + description: | + ## 概要 + 日付とそれに対応した複数loginで構成されるシフト配列をDBに反映する requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/addShiftsRequestBody' + $ref: './openapi.yml#/components/schemas/addShiftsRequestBody' required: - shift responses: '200': - description: "成功。追加した日付一覧をjsonで返します" + description: "追加した日付の配列を返却する" content: application/json: schema: - $ref: '#/components/schemas/addShiftsResponse' + $ref: './openapi.yml#/components/schemas/addShiftsResponse' '400': - description: "失敗。エラーメッセージをjsonで返します" + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error400' + '404': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error404' + '500': + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error500' delete: + tags: + - シフト管理 summary: "シフトの削除" - description: "特定の日付とそれに対応したloginのシフトを論理削除します。" + description: | + ## 概要 + 日付とそれに対応したloginのシフトを論理削除する requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/deleteShiftsRequestBody' + $ref: './openapi.yml#/components/schemas/deleteShiftsRequestBody' required: - login - date responses: '200': - description: "成功。削除したシフトをjsonで返します" + description: "削除したシフトを返却する" content: application/json: schema: - $ref: '#/components/schemas/Shift' + $ref: './openapi.yml#/components/schemas/Shift' '400': - description: "失敗。エラーメッセージをjsonで返します" + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error400' + '404': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error404' + '500': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error500' /shifts/exchange: post: + tags: + - シフト管理 summary: "シフトの交換" - description: "特定のシフトの担当者を交換します" + description: | + ## 概要 + 特定のシフトの担当者を交換する requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/exchangeShiftsRequestBody' + $ref: './openapi.yml#/components/schemas/exchangeShiftsRequestBody' required: - login1 - login2 @@ -95,196 +141,325 @@ paths: - date2 responses: '200': - description: "成功。交換後のシフトの配列を返します" + description: "交換後の交換対象者のシフトを返却する" content: application/json: schema: - $ref: '#/components/schemas/shiftsArray' + $ref: './openapi.yml#/components/schemas/shiftsArray' '400': - description: "失敗。エラーメッセージをjsonで返します" + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error400' + '404': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error404' + '500': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error500' /users: post: + tags: + - ユーザ管理 summary: "ユーザの追加" - description: "任意人数のlogin, uid, walletをDBに追加します" + description: | + ## 概要 + 複数人のユーザの追加/更新を行う + ## 注意点 + 処理中にエラーが発生した場合、ロールバックは行われない + DBにすでに存在し、情報の更新がないユーザはスキップされる requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/usersArray' + $ref: './openapi.yml#/components/schemas/usersArray' required: - users responses: '200': - description: "成功。追加したuserの配列をjsonで返します" + description: "追加/更新したuserの配列を返却する" content: application/json: schema: - $ref: '#/components/schemas/usersArray' + $ref: './openapi.yml#/components/schemas/usersArray' '400': - description: "失敗。エラーメッセージと追加に成功したuserの配列をjsonで返します" + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error400' + '500': + description: | + エラーメッセージと追加/更新に成功したuserの配列を返却する content: application/json: schema: type: object properties: - error: {type: string, example: "Error message"} + error: {type: string, example: "Internal Server Error."} users: {type: array, example: ["a", "b", "c"]} put: + tags: + - ユーザ管理 summary: "ユーザの編集" - description: "intra名に紐づくuidやwalletアドレスを更新します" + description: | + ## 概要 + intra名に紐づくuidとwalletアドレスを更新する requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/UserData' + $ref: './openapi.yml#/components/schemas/UserData' required: - login responses: '200': - description: "成功。更新したユーザをjsonで返します" + description: "" content: application/json: schema: - $ref: '#/components/schemas/UserData' + $ref: './openapi.yml#/components/schemas/UserData' '400': - description: "失敗。エラーメッセージをjsonで返します" + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error400' + '404': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error404' + '500': + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error500' /activities: post: + tags: + - アクティビティ管理 summary: "アクティビティの追加" + description: | + ## 概要 + 42学生のアクティビティ(掃除など)を追加する + 主にNFCタグを読み取った際にM5Stickが実行する requestBody: required: true + description: | + mac: M5Stickのmacアドレス + uid: 42学生を識別するuid content: application/json: schema: - $ref: '#/components/schemas/ActivityData' + $ref: './openapi.yml#/components/schemas/ActivityData' required: - mac - uid responses: '200': - description: "成功。uidとmacをjsonで返します" + description: "使用したuidとmacアドレスを返却する" content: application/json: schema: - $ref: '#/components/schemas/ActivityData' + $ref: './openapi.yml#/components/schemas/ActivityData' '400': - description: "失敗。エラーメッセージをjsonで返します" + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error400' + '404': + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error404' + '500': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error500' /activities/cleanings: get: - summary: "掃除データの取得" - description: "指定した期間でrole(cleaning)に紐づくデータを返します" + tags: + - アクティビティ管理 + summary: "掃除アクティビティの取得" + description: | + ## 概要 + 指定した期間で、M5Stickのroleがcleaningのアクティビティを返却する + 期間の指定を行わない場合、現在の日付の午前0時から24時間分のデータを返却する parameters: - name: start in: query required: false - description: "絞り込む期間の開始時刻(Unix秒)、未指定の場合は現在の日付の午前0時" + description: | + 絞り込む期間の開始時刻(Unix秒) + 未指定の場合は現在の日付の午前0時に設定される schema: {type: string, example: '1711966578', default: '1711897200'} - name: end in: query required: false - description: "絞り込む期間の終了時刻(Unix秒)、未指定の場合はstart+24時間" + description: | + 絞り込む期間の終了時刻(Unix秒) + 未指定の場合はstart+24時間に設定される schema: {type: string, example: '1713176178', default: '1711983600'} responses: '200': - description: "成功。掃除データをjsonで返します" + description: "" content: application/json: schema: - $ref: '#/components/schemas/cleaningsData' + $ref: './openapi.yml#/components/schemas/cleaningsData' '400': - description: "失敗。エラーメッセージをjsonで返します" + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error400' + '404': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error404' + '500': + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error500' /roles: post: + tags: + - ロール管理 summary: "ロールの追加" + description: | + ## 概要 + M5Stickの役割を識別するroleを追加する requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/RoleData' + $ref: './openapi.yml#/components/schemas/RoleData' required: - name responses: '200': - description: "成功。追加したロールをjsonで返します" + description: "追加したroleを返却する" content: application/json: schema: - $ref: '#/components/schemas/RoleData' - '400': - description: "失敗。エラーメッセージをjsonで返します" + $ref: './openapi.yml#/components/schemas/RoleData' + '409': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error409' + '500': + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error500' /locations: post: + tags: + - ロケーション管理 summary: "場所の追加" + description: | + ## 概要 + M5Stickの設置場所を追加する requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/LocationData' + $ref: './openapi.yml#/components/schemas/LocationData' required: - name responses: '200': - description: "成功。追加した場所をjsonで返します" + description: "追加した設置場所を返却する" content: application/json: schema: - $ref: '#/components/schemas/LocationData' - '400': - description: "失敗。エラーメッセージをjsonで返します" + $ref: './openapi.yml#/components/schemas/LocationData' + '409': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error409' + '500': + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error500' /m5sticks: post: + tags: + - M5Stick端末管理 summary: "M5Stickの追加" + description: | + ## 概要 + M5Stickのmacアドレス、role、locationを追加する requestBody: required: true content: application/json: schema: - $ref: '#/components/schemas/M5StickData' + $ref: './openapi.yml#/components/schemas/M5StickData' required: - mac - role - location responses: '200': - description: "成功。追加したM5Stickをjsonで返します" + description: "追加したM5Stickのデータを返却する" content: application/json: schema: - $ref: '#/components/schemas/M5StickData' + $ref: './openapi.yml#/components/schemas/M5StickData' '400': - description: "失敗。エラーメッセージをjsonで返します" + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error400' + '404': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error404' + '409': + description: "" + content: + application/json: + schema: + $ref: './openapi.yml#/components/schemas/Error409' + '500': + description: "" content: application/json: schema: - $ref: '#/components/schemas/Error' + $ref: './openapi.yml#/components/schemas/Error500' components: schemas: shiftsArray: @@ -293,7 +468,7 @@ components: type: object properties: shifts: - $ref: '#/components/schemas/Shift' + $ref: './openapi.yml#/components/schemas/Shift' addShiftsRequestBody: type: array items: @@ -343,7 +518,7 @@ components: users: type: array items: - $ref: '#/components/schemas/UserData' + $ref: './openapi.yml#/components/schemas/UserData' addShiftsResponse: type: object properties: @@ -361,10 +536,10 @@ components: ID: {type: integer, example: 1} UserID: {type: integer, example: 1} User: - $ref: '#/components/schemas/User' + $ref: './openapi.yml#/components/schemas/User' M5StickID: {type: integer, example: 1} M5Stick: - $ref: '#/components/schemas/M5Stick' + $ref: './openapi.yml#/components/schemas/M5Stick' CreatedAt: {type: integer, example: 1712666900} User: type: object @@ -380,7 +555,7 @@ components: Date: {type: string, example: "2024-05-01"} UserID: {type: integer, example: 1} User: - $ref: '#/components/schemas/User' + $ref: './openapi.yml#/components/schemas/User' DeletedAt: {type: string, example: "2024-06-19T11:55:03.892Z"} M5Stick: type: object @@ -389,10 +564,10 @@ components: Mac: {type: string, example: "00:00:00:00:00:00"} RoleId: {type: integer, example: 1} Role: - $ref: '#/components/schemas/Role' + $ref: './openapi.yml#/components/schemas/Role' LocationId: {type: integer, example: 1} Location: - $ref: '#/components/schemas/Location' + $ref: './openapi.yml#/components/schemas/Location' Role: type: object properties: @@ -423,7 +598,19 @@ components: mac: {type: string, example: "00:00:00:00:00:00"} role: {type: string, example: "Cleaning"} location: {type: string, example: "F1"} - Error: + Error400: + type: object + properties: + error: {type: string, example: "Bad Request."} + Error404: + type: object + properties: + error: {type: string, example: "Not Found."} + Error409: + type: object + properties: + error: {type: string, example: "Conflict."} + Error500: type: object properties: - error: {type: string, example: "Error message"} + error: {type: string, example: "Internal Server Error."} diff --git a/cmd/ft_activity_api/main.go b/cmd/ft_activity_api/main.go index c822026..444796c 100644 --- a/cmd/ft_activity_api/main.go +++ b/cmd/ft_activity_api/main.go @@ -6,6 +6,8 @@ import ( "42ActivityAPI/internal/loadconfig" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" + "github.com/swaggo/files" + "github.com/swaggo/gin-swagger" "log" "net/http" "os" @@ -27,6 +29,17 @@ func main() { config.AllowOrigins = []string{"*"} router.Use(cors.New(config)) + // Swagger-ui settings + router.StaticFile("/openapi.yml", "./api/openapi/openapi.yml") + router.GET("/apidoc/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, + ginSwagger.DefaultModelsExpandDepth(-1), + func(c *ginSwagger.Config) { + c.URL = "/openapi.yml" + })) + router.GET("/apidoc", func(c *gin.Context) { + c.Redirect(302, "/apidoc/index.html") + }) + router.GET("/", ShowIndexPage) router.GET("/new", RedirectToIndexWithUID) router.GET("/callback", ShowCallbackPage) diff --git a/go.mod b/go.mod index a961833..a0fb5c6 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,8 @@ require ( github.com/go-sql-driver/mysql v1.8.1 github.com/jinzhu/now v1.1.5 github.com/stretchr/testify v1.9.0 + github.com/swaggo/files v1.0.1 + github.com/swaggo/gin-swagger v1.6.0 gorm.io/driver/mysql v1.5.6 gorm.io/driver/sqlite v1.5.5 gorm.io/gorm v1.25.10 @@ -16,6 +18,9 @@ require ( require ( filippo.io/edwards25519 v1.1.0 // indirect + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/PuerkitoBio/purell v1.1.1 // indirect + github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect github.com/bytedance/sonic v1.11.6 // indirect github.com/bytedance/sonic/loader v0.1.1 // indirect github.com/cloudwego/base64x v0.1.4 // indirect @@ -24,6 +29,10 @@ require ( github.com/dustin/go-humanize v1.0.1 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.19.6 // indirect + github.com/go-openapi/spec v0.20.4 // indirect + github.com/go-openapi/swag v0.19.15 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.20.0 // indirect @@ -31,10 +40,11 @@ require ( github.com/google/uuid v1.6.0 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/jinzhu/inflection v1.0.0 // indirect + github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.7 // indirect - github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect + github.com/mailru/easyjson v0.7.6 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-sqlite3 v1.14.17 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect @@ -43,6 +53,7 @@ require ( github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/swaggo/swag v1.8.12 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect golang.org/x/arch v0.8.0 // indirect @@ -50,7 +61,9 @@ require ( golang.org/x/net v0.25.0 // indirect golang.org/x/sys v0.20.0 // indirect golang.org/x/text v0.15.0 // indirect + golang.org/x/tools v0.19.0 // indirect google.golang.org/protobuf v1.34.1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect modernc.org/libc v1.50.9 // indirect diff --git a/go.sum b/go.sum index 47057a2..2f849dc 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,11 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= @@ -18,10 +24,22 @@ github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uq github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw= github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E= +github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4= +github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs= +github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= +github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M= +github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= @@ -48,18 +66,27 @@ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM= @@ -71,6 +98,7 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -84,6 +112,7 @@ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSS github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= @@ -91,35 +120,76 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= +github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg= +github.com/swaggo/gin-swagger v1.6.0 h1:y8sxvQ3E20/RCyrXeFfg60r6H0Z+SwpTjMYsMm+zy8M= +github.com/swaggo/gin-swagger v1.6.0/go.mod h1:BG00cCEy294xtVpyIAHG6+e2Qzj/xKlRdOqDkvq0uzo= +github.com/swaggo/swag v1.8.12 h1:pctzkNPu0AlQP2royqX3apjKCQonAnf7KGoxeO4y64w= +github.com/swaggo/swag v1.8.12/go.mod h1:lNfm6Gg+oAq3zRJQNEMBE66LIJKM44mxFqhEEgy2its= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw= golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gorm.io/driver/mysql v1.5.6 h1:Ld4mkIickM+EliaQZQx3uOJDJHtrd70MxAUqWqlx3Y8= diff --git a/internal/accessdb/activity_db.go b/internal/accessdb/activity_db.go index 947390c..d32a481 100644 --- a/internal/accessdb/activity_db.go +++ b/internal/accessdb/activity_db.go @@ -10,10 +10,10 @@ import ( Receives start_time, end_time, and role, and returns activities that were created between start_time, and end_time and have a matching M5stick role. */ -func GetActivitiesFromDB(start_time int64, end_time int64, role string) ([]Activity, error) { +func GetActivitiesFromDB(start_time int64, end_time int64, role string) ([]Activity, error, int) { db, err := ConnectToDB() if err != nil { - return nil, err + return nil, err, 500 } var activities []Activity err = db. @@ -23,9 +23,12 @@ func GetActivitiesFromDB(start_time int64, end_time int64, role string) ([]Activ Where("roles.name = ?", role). Find(&activities).Error if err != nil { - return nil, err + if err == gorm.ErrRecordNotFound { + return nil, err, 404 + } + return nil, err, 500 } - return activities, nil + return activities, nil, 200 } // Receive the uid and MAC address, and add a new activity. diff --git a/internal/accessdb/location_db.go b/internal/accessdb/location_db.go index cab7be6..d3c1ca2 100644 --- a/internal/accessdb/location_db.go +++ b/internal/accessdb/location_db.go @@ -6,24 +6,24 @@ import ( ) // Receive the location name, and if it does not exist in the DB, add a new location. -func AddLocationToDB(locationName string) error { +func AddLocationToDB(locationName string) (error, int) { db, err := ConnectToDB() if err != nil { - return err + return err, 500 } var existingLocation Location if err := db.Where("name = ?", locationName).First(&existingLocation).Error; err != nil { if err != gorm.ErrRecordNotFound { - return err + return err, 500 } } else { - return errors.New("Location already exists") + return errors.New("Location already exists"), 409 } location := Location{Name: locationName} if result := db.Create(&location); result.Error != nil { - return result.Error + return result.Error, 500 } - return nil + return nil, 200 } diff --git a/internal/accessdb/m5stick_db.go b/internal/accessdb/m5stick_db.go index 928bf32..388290b 100644 --- a/internal/accessdb/m5stick_db.go +++ b/internal/accessdb/m5stick_db.go @@ -9,35 +9,41 @@ import ( Receives the MAC address, role name, and location name, and if the same MAC address does not exist in the DB, adds a new M5stick */ -func AddM5StickToDB(mac string, roleName string, locationName string) error { +func AddM5StickToDB(mac string, roleName string, locationName string) (error, int) { db, err := ConnectToDB() if err != nil { - return err + return err, 500 } var existingM5Stick M5Stick if err := db.Where("mac = ?", mac).First(&existingM5Stick).Error; err != nil { if err != gorm.ErrRecordNotFound { - return err + return err, 500 } } else { - return errors.New("M5Stick already exists") + return errors.New("M5Stick already exists"), 409 } var role Role if err := db.Where("name = ?", roleName).First(&role).Error; err != nil { - return err + if err == gorm.ErrRecordNotFound { + return errors.New("Role does not exist"), 404 + } + return err, 500 } var location Location if err := db.Where("name = ?", locationName).First(&location).Error; err != nil { - return err + if err == gorm.ErrRecordNotFound { + return errors.New("Location does not exist"), 404 + } + return err, 500 } m5Stick := M5Stick{Mac: mac, RoleId: role.ID, LocationId: location.ID} if result := db.Create(&m5Stick); result.Error != nil { - return result.Error + return result.Error, 500 } - return nil + return nil, 200 } diff --git a/internal/accessdb/role_db.go b/internal/accessdb/role_db.go index b2fb808..5b69eb2 100644 --- a/internal/accessdb/role_db.go +++ b/internal/accessdb/role_db.go @@ -6,24 +6,24 @@ import ( ) // Receive the role name, and if it does not exist in the DB, add a new role. -func AddRoleToDB(roleName string) error { +func AddRoleToDB(roleName string) (error, int) { db, err := ConnectToDB() if err != nil { - return err + return err, 500 } var existingRole Role if err := db.Where("name = ?", roleName).First(&existingRole).Error; err != nil { if err != gorm.ErrRecordNotFound { - return err + return err, 500 } } else { - return errors.New("Role already exists") + return errors.New("Role already exists"), 409 } role := Role{Name: roleName} if result := db.Create(&role); result.Error != nil { - return result.Error + return result.Error, 500 } - return nil + return nil, 200 } diff --git a/internal/accessdb/shift_db.go b/internal/accessdb/shift_db.go index 9d78ba2..cea7d8c 100644 --- a/internal/accessdb/shift_db.go +++ b/internal/accessdb/shift_db.go @@ -22,10 +22,10 @@ func GetShiftFromDB(date string) ([]Shift, error) { Receives an array of shifts, adds a shift that does not exist in the DB, and returns an array of added dates. */ -func AddShiftToDB(schedule []Schedule) ([]string, error) { +func AddShiftToDB(schedule []Schedule) ([]string, error, int) { db, err := ConnectToDB() if err != nil { - return nil, err + return nil, err, 500 } var addedDate []string @@ -37,18 +37,18 @@ func AddShiftToDB(schedule []Schedule) ([]string, error) { } flag = false for _, l := range s.Login { - userId, err := getUserIdFromLogin(db, l) + userId, err, status := getUserIdFromLogin(db, l) if err != nil { - return nil, err + return nil, err, status } var shift Shift if err := db.Where("user_id = ? AND date = ?", userId, s.Date).First(&shift).Error; err != nil { if err != gorm.ErrRecordNotFound { - return nil, err + return nil, err, 500 } shift = Shift{Date: s.Date, UserID: userId} if result := db.Create(&shift); result.Error != nil { - return nil, result.Error + return nil, result.Error, 500 } flag = true } else { @@ -59,41 +59,50 @@ func AddShiftToDB(schedule []Schedule) ([]string, error) { addedDate = append(addedDate, s.Date) } } - return addedDate, nil + return addedDate, nil, 200 } // Receive the login and *gorm.DB, and return the user ID. -func getUserIdFromLogin(db *gorm.DB, login string) (int, error) { +func getUserIdFromLogin(db *gorm.DB, login string) (int, error, int) { var user User if err := db.Where("login = ?", login).First(&user).Error; err != nil { - return 0, err + if err == gorm.ErrRecordNotFound { + return 0, err, 404 + } + return 0, err, 500 } - return user.ID, nil + return user.ID, nil, 200 } // Receives login and date, exchanges the shift, and returns the exchanged shift. -func ExchangeShiftsOnDB(login1, login2, date1, date2 string) (*Shift, *Shift, error) { +func ExchangeShiftsOnDB(login1, login2, date1, date2 string) (*Shift, *Shift, error, int) { db, err := ConnectToDB() if err != nil { - return nil, nil, err + return nil, nil, err, 500 } - shift1, shift2, err := transactionExchange(db, login1, login2, date1, date2) + shift1, shift2, err, status := transactionExchange(db, login1, login2, date1, date2) if err != nil { - return nil, nil, err + return nil, nil, err, status } - return shift1, shift2, nil + return shift1, shift2, nil, 200 } -func transactionExchange(db *gorm.DB, login1, login2, date1, date2 string) (*Shift, *Shift, error) { +func transactionExchange(db *gorm.DB, login1, login2, date1, date2 string) (*Shift, *Shift, error, int) { var shift1, shift2 Shift err := db.Transaction(func(tx *gorm.DB) error { - userId1, err := getUserIdFromLogin(tx, login1) + userId1, err, status := getUserIdFromLogin(tx, login1) if err != nil { + if status == 404 { + return gorm.ErrRecordNotFound + } return err } - userId2, err := getUserIdFromLogin(tx, login2) + userId2, err, status := getUserIdFromLogin(tx, login2) if err != nil { + if status == 404 { + return gorm.ErrRecordNotFound + } return err } if err := tx.Where("user_id = ? AND date = ?", userId1, date1).First(&shift1).Error; err != nil { @@ -117,29 +126,35 @@ func transactionExchange(db *gorm.DB, login1, login2, date1, date2 string) (*Shi return nil }, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { - return nil, nil, err + if err == gorm.ErrRecordNotFound { + return nil, nil, err, 404 + } + return nil, nil, err, 500 } - return &shift1, &shift2, nil + return &shift1, &shift2, nil, 200 } // Receives login and date, deletes the shift, and returns the deleted shift. -func DeleteShiftFromDB(login, date string) (*Shift, error) { +func DeleteShiftFromDB(login, date string) (*Shift, error, int) { db, err := ConnectToDB() if err != nil { - return nil, err + return nil, err, 500 } - shift, err := transactionDelete(db, login, date) + shift, err, status := transactionDelete(db, login, date) if err != nil { - return nil, err + return nil, err, status } - return shift, nil + return shift, nil, 200 } -func transactionDelete(db *gorm.DB, login, date string) (*Shift, error) { +func transactionDelete(db *gorm.DB, login, date string) (*Shift, error, int) { var shift Shift err := db.Transaction(func(tx *gorm.DB) error { - userId, err := getUserIdFromLogin(tx, login) + userId, err, status := getUserIdFromLogin(tx, login) if err != nil { + if status == 404 { + return gorm.ErrRecordNotFound + } return err } if err := tx.Where("user_id = ? AND date = ?", userId, date).First(&shift).Error; err != nil { @@ -154,7 +169,10 @@ func transactionDelete(db *gorm.DB, login, date string) (*Shift, error) { return nil }, &sql.TxOptions{Isolation: sql.LevelSerializable}) if err != nil { - return nil, err + if err == gorm.ErrRecordNotFound { + return nil, err, 404 + } + return nil, err, 500 } - return &shift, nil + return &shift, nil, 200 } diff --git a/internal/accessdb/user_db.go b/internal/accessdb/user_db.go index 11e6687..c0cbd46 100644 --- a/internal/accessdb/user_db.go +++ b/internal/accessdb/user_db.go @@ -41,23 +41,27 @@ func AddUsersToDB(users []UserRequestData) ([]string, error) { } // Receive uid, login, and wallet, and if the same login exists in the DB, update the user data. -func EditUserInDB(uid string, login string, wallet string) error { +func EditUserInDB(uid string, login string, wallet string) (error, int) { db, err := ConnectToDB() if err != nil { - return err + return err, 500 } var existingUser User if err := db.Where("login = ?", login).First(&existingUser).Error; err != nil { - return err + if err == gorm.ErrRecordNotFound { + return errors.New("User not found"), 404 + } + return err, 500 } if result := db.Model(&existingUser).Updates(User{UID: uid, Wallet: wallet}); result.Error != nil { - return result.Error + return result.Error, 500 } - return nil + return nil, 200 } +// // Receives uid, login, and wallet, and if the same login does not exist in the DB, adds a new user. func AddUserToDB(uid string, login string, wallet string) error { db, err := ConnectToDB() diff --git a/internal/handlers/activities.go b/internal/handlers/activities.go index 3d29ee1..1891641 100644 --- a/internal/handlers/activities.go +++ b/internal/handlers/activities.go @@ -18,13 +18,17 @@ type ActivityRequestData struct { func GetActivityCleanData(c *gin.Context) { start_time, end_time, err := GetQueryAboutTime(c) if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid query"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } - Activities, err := accessdb.GetActivitiesFromDB(start_time, end_time, "cleaning") + Activities, err, status := accessdb.GetActivitiesFromDB(start_time, end_time, "cleaning") if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get activities"}) + if status == http.StatusNotFound { + c.JSON(status, gin.H{"error": "Not Found."}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error."}) return } c.JSON(http.StatusOK, Activities) @@ -35,22 +39,26 @@ func AddActivity(c *gin.Context) { var requestData ActivityRequestData if err := c.BindJSON(&requestData); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if requestData.Mac == "" || requestData.Uid == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "All parameters are required"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } status, uid, mac, err := accessdb.AddActivityToDB(requestData.Uid, requestData.Mac) if err != nil { - c.JSON(status, gin.H{"error": err.Error()}) + if status == http.StatusNotFound { + c.JSON(status, gin.H{"error": "Not Found."}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error."}) return } - c.JSON(status, gin.H{"uid": uid, "mac": mac}) + c.JSON(http.StatusOK, gin.H{"uid": uid, "mac": mac}) return } diff --git a/internal/handlers/locations.go b/internal/handlers/locations.go index 6beb688..6d516d1 100644 --- a/internal/handlers/locations.go +++ b/internal/handlers/locations.go @@ -15,15 +15,19 @@ func AddLocation(c *gin.Context) { var requestData LocationRequestData if err := c.BindJSON(&requestData); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if requestData.Name == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "Location is required"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } - if err := accessdb.AddLocationToDB(requestData.Name); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + if err, status := accessdb.AddLocationToDB(requestData.Name); err != nil { + if status == http.StatusConflict { + c.JSON(http.StatusConflict, gin.H{"error": "Conflict."}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error."}) return } c.JSON(http.StatusOK, gin.H{"name": requestData.Name}) diff --git a/internal/handlers/m5sticks.go b/internal/handlers/m5sticks.go index d0340bd..8624b46 100644 --- a/internal/handlers/m5sticks.go +++ b/internal/handlers/m5sticks.go @@ -17,15 +17,23 @@ func AddM5Stick(c *gin.Context) { var requestData M5StickRequestData if err := c.BindJSON(&requestData); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if requestData.Mac == "" || requestData.RoleName == "" || requestData.LocationName == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "All parameters are required"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } - if err := accessdb.AddM5StickToDB(requestData.Mac, requestData.RoleName, requestData.LocationName); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + if err, status := accessdb.AddM5StickToDB(requestData.Mac, requestData.RoleName, requestData.LocationName); err != nil { + if status == http.StatusConflict { + c.JSON(http.StatusConflict, gin.H{"error": "Conflict."}) + return + } + if status == http.StatusNotFound { + c.JSON(http.StatusNotFound, gin.H{"error": "Not Found."}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error."}) return } c.JSON(http.StatusOK, gin.H{"mac": requestData.Mac, "role": requestData.RoleName, "location": requestData.LocationName}) diff --git a/internal/handlers/roles.go b/internal/handlers/roles.go index 1973926..c5ce12e 100644 --- a/internal/handlers/roles.go +++ b/internal/handlers/roles.go @@ -15,15 +15,19 @@ func AddRole(c *gin.Context) { var requestData RoleRequestData if err := c.BindJSON(&requestData); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if requestData.Name == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "Role is required"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } - if err := accessdb.AddRoleToDB(requestData.Name); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + if err, status := accessdb.AddRoleToDB(requestData.Name); err != nil { + if status == http.StatusConflict { + c.JSON(http.StatusConflict, gin.H{"error": "Conflict."}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error."}) return } c.JSON(http.StatusOK, gin.H{"name": requestData.Name}) diff --git a/internal/handlers/shifts.go b/internal/handlers/shifts.go index 8f4d304..80a11b2 100644 --- a/internal/handlers/shifts.go +++ b/internal/handlers/shifts.go @@ -25,13 +25,13 @@ type DeleteData struct { func GetShiftData(c *gin.Context) { date, err := getQueryAboutDate(c) if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid query"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } shifts, err := accessdb.GetShiftFromDB(date) if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get shift"}) + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error."}) return } c.JSON(http.StatusOK, gin.H{"shifts": shifts}) @@ -42,15 +42,19 @@ func AddShiftData(c *gin.Context) { var schedule []accessdb.Schedule if err := c.BindJSON(&schedule); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if len(schedule) == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "Shift is required"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } - if date, err := accessdb.AddShiftToDB(schedule); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + if date, err, status := accessdb.AddShiftToDB(schedule); err != nil { + if status == http.StatusNotFound { + c.JSON(http.StatusNotFound, gin.H{"error": "Not Found."}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error."}) return } else { c.JSON(http.StatusOK, gin.H{"date": date}) @@ -77,19 +81,23 @@ func isDateStringValid(date string) bool { func ExchangeShiftData(c *gin.Context) { var e ExchangeData if err := c.BindJSON(&e); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if e.Login1 == "" || e.Login2 == "" || e.Date1 == "" || e.Date2 == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "login1, login2, date1, and date2 are required"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if !isDateStringValid(e.Date1) || !isDateStringValid(e.Date2) { - c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid date format. It should be in YYYY-MM-DD format"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } - if shift1, shift2, err := accessdb.ExchangeShiftsOnDB(e.Login1, e.Login2, e.Date1, e.Date2); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + if shift1, shift2, err, status := accessdb.ExchangeShiftsOnDB(e.Login1, e.Login2, e.Date1, e.Date2); err != nil { + if status == http.StatusNotFound { + c.JSON(http.StatusNotFound, gin.H{"error": "Not Found."}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error."}) return } else { c.JSON(http.StatusOK, gin.H{ @@ -102,19 +110,23 @@ func ExchangeShiftData(c *gin.Context) { func DeleteShiftData(c *gin.Context) { var d DeleteData if err := c.BindJSON(&d); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if d.Login == "" || d.Date == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "login and date are required"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if !isDateStringValid(d.Date) { - c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid date format. It should be in YYYY/MM/DD format"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } - if shift, err := accessdb.DeleteShiftFromDB(d.Login, d.Date); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + if shift, err, status := accessdb.DeleteShiftFromDB(d.Login, d.Date); err != nil { + if status == http.StatusNotFound { + c.JSON(http.StatusNotFound, gin.H{"error": "Not Found."}) + return + } + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } else { c.JSON(http.StatusOK, shift) diff --git a/internal/handlers/users.go b/internal/handlers/users.go index 600eab1..f2bbace 100644 --- a/internal/handlers/users.go +++ b/internal/handlers/users.go @@ -11,15 +11,15 @@ func AddUsers(c *gin.Context) { var requestData accessdb.Users if err := c.BindJSON(&requestData); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if len(requestData.Users) == 0 { - c.JSON(http.StatusBadRequest, gin.H{"error": "User is not specified"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if addedLogin, err := accessdb.AddUsersToDB(requestData.Users); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "users": addedLogin}) + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error.", "users": addedLogin}) return } else { c.JSON(http.StatusOK, gin.H{"users": addedLogin}) @@ -32,15 +32,19 @@ func EditUser(c *gin.Context) { var requestData accessdb.UserRequestData if err := c.BindJSON(&requestData); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } if requestData.Login == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "Login is required"}) + c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request."}) return } - if err := accessdb.EditUserInDB(requestData.Uid, requestData.Login, requestData.Wallet); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + if err, status := accessdb.EditUserInDB(requestData.Uid, requestData.Login, requestData.Wallet); err != nil { + if status == 404 { + c.JSON(http.StatusNotFound, gin.H{"error": "Not Found."}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal Server Error."}) return } response := make(gin.H)