diff --git a/cmd/genopenapi/main.go b/cmd/genopenapi/main.go new file mode 100644 index 0000000000..ed655eb932 --- /dev/null +++ b/cmd/genopenapi/main.go @@ -0,0 +1,33 @@ +// Copyright 2024 Democratized Data Foundation +// +// Use of this software is governed by the Business Source License +// included in the file licenses/BSL.txt. +// +// As of the Change Date specified in that file, in accordance with +// the Business Source License, use of this software will be governed +// by the Apache License, Version 2.0, included in the file +// licenses/APL.txt. + +/* +genopenapi is a tool to generate and print an OpenAPI specification. +*/ +package main + +import ( + "fmt" + "os" + + "github.com/sourcenetwork/defradb/http" +) + +func main() { + router, err := http.NewApiRouter() + if err != nil { + panic(err) + } + json, err := router.OpenAPI().MarshalJSON() + if err != nil { + panic(err) + } + fmt.Fprint(os.Stdout, string(json)) +} diff --git a/http/handler.go b/http/handler.go index 1df8987964..328ea8fab9 100644 --- a/http/handler.go +++ b/http/handler.go @@ -29,15 +29,7 @@ var Version string = "v0" // playgroundHandler is set when building with the playground build tag var playgroundHandler http.Handler = http.HandlerFunc(http.NotFound) -type Handler struct { - db client.DB - mux *chi.Mux - txs *sync.Map -} - -func NewHandler(db client.DB, opts ServerOptions) (*Handler, error) { - txs := &sync.Map{} - +func NewApiRouter() (*Router, error) { tx_handler := &txHandler{} store_handler := &storeHandler{} collection_handler := &collectionHandler{} @@ -50,12 +42,6 @@ func NewHandler(db client.DB, opts ServerOptions) (*Handler, error) { return nil, err } - router.AddMiddleware( - ApiMiddleware(db, txs, opts), - TransactionMiddleware, - StoreMiddleware, - ) - tx_handler.bindRoutes(router) store_handler.bindRoutes(router) p2p_handler.bindRoutes(router) @@ -74,6 +60,21 @@ func NewHandler(db client.DB, opts ServerOptions) (*Handler, error) { if err := router.Validate(context.Background()); err != nil { return nil, err } + return router, nil +} + +type Handler struct { + db client.DB + mux *chi.Mux + txs *sync.Map +} + +func NewHandler(db client.DB, opts ServerOptions) (*Handler, error) { + router, err := NewApiRouter() + if err != nil { + return nil, err + } + txs := &sync.Map{} mux := chi.NewMux() mux.Use( @@ -81,7 +82,14 @@ func NewHandler(db client.DB, opts ServerOptions) (*Handler, error) { middleware.Recoverer, CorsMiddleware(opts), ) - mux.Mount("/api/"+Version, router) + mux.Route("/api/"+Version, func(r chi.Router) { + r.Use( + ApiMiddleware(db, txs, opts), + TransactionMiddleware, + StoreMiddleware, + ) + r.Handle("/*", router) + }) mux.Get("/openapi.json", func(rw http.ResponseWriter, req *http.Request) { responseJSON(rw, http.StatusOK, router.OpenAPI()) })