harness-drone/handler/api/user/sync.go
2019-02-19 15:56:41 -08:00

55 lines
1.5 KiB
Go

// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
package user
import (
"context"
"net/http"
"github.com/drone/drone/handler/api/render"
"github.com/drone/drone/handler/api/request"
"github.com/drone/drone/logger"
"github.com/drone/drone/core"
)
// HandleSync returns an http.HandlerFunc synchronizes and then
// write a json-encoded list of repositories to the response body.
func HandleSync(syncer core.Syncer, repos core.RepositoryStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
viewer, _ := request.UserFrom(r.Context())
// performs asyncrhonous account synchronization.
// this requires long polling to determine when the
// sync is complete.
if r.Header.Get("async") == "true" {
ctx := r.Context()
go func(ctx context.Context, viewer *core.User) {
_, err := syncer.Sync(ctx, viewer)
if err != nil {
logger.FromContext(ctx).WithError(err).
Debugln("api: cannot synchrnoize account")
}
}(ctx, viewer)
w.WriteHeader(204)
return
}
_, err := syncer.Sync(r.Context(), viewer)
if err != nil {
render.InternalError(w, err)
logger.FromRequest(r).WithError(err).
Warnln("api: cannot synchrnoize account")
return
}
list, err := repos.List(r.Context(), viewer.ID)
if err != nil {
render.InternalError(w, err)
logger.FromRequest(r).WithError(err).
Warnln("api: cannot synchrnoize account")
} else {
render.JSON(w, list, 200)
}
}
}