Files
coder/httpmw/projectparam.go
T
Kyle Carberry 5b01f615eb feat: Add APIs for querying workspaces (#61)
* Add SQL migration

* Add query functions for workspaces

* Add create routes

* Add tests for codersdk

* Add workspace parameter route

* Add workspace query

* Move workspace function

* Add querying for workspace history

* Fix query

* Fix syntax error

* Move workspace routes

* Fix version

* Add CLI tests

* Fix syntax error

* Remove error

* Fix history error

* Add new user test

* Fix test

* Lower target to 70%

* Improve comments

* Add comment
2022-01-25 19:52:58 +00:00

61 lines
1.7 KiB
Go

package httpmw
import (
"context"
"database/sql"
"errors"
"fmt"
"net/http"
"github.com/go-chi/chi"
"github.com/coder/coder/database"
"github.com/coder/coder/httpapi"
)
type projectParamContextKey struct{}
// ProjectParam returns the project from the ExtractProjectParam handler.
func ProjectParam(r *http.Request) database.Project {
project, ok := r.Context().Value(projectParamContextKey{}).(database.Project)
if !ok {
panic("developer error: project param middleware not provided")
}
return project
}
// ExtractProjectParam grabs a project from the "project" URL parameter.
func ExtractProjectParam(db database.Store) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
organization := OrganizationParam(r)
projectName := chi.URLParam(r, "project")
if projectName == "" {
httpapi.Write(rw, http.StatusBadRequest, httpapi.Response{
Message: "project name must be provided",
})
return
}
project, err := db.GetProjectByOrganizationAndName(r.Context(), database.GetProjectByOrganizationAndNameParams{
OrganizationID: organization.ID,
Name: projectName,
})
if errors.Is(err, sql.ErrNoRows) {
httpapi.Write(rw, http.StatusNotFound, httpapi.Response{
Message: fmt.Sprintf("project %q does not exist", projectName),
})
return
}
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, httpapi.Response{
Message: fmt.Sprintf("get project: %s", err.Error()),
})
return
}
ctx := context.WithValue(r.Context(), projectParamContextKey{}, project)
next.ServeHTTP(rw, r.WithContext(ctx))
})
}
}