github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/services/authorizations/list.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package authorizations
    19  
    20  import (
    21  	"github.com/aacfactory/errors"
    22  	"github.com/aacfactory/fns/context"
    23  	"github.com/aacfactory/fns/runtime"
    24  	"github.com/aacfactory/fns/services"
    25  )
    26  
    27  var (
    28  	listFnName = []byte("list")
    29  )
    30  
    31  func List(ctx context.Context, account Id) (v []Authorization, err error) {
    32  	rt := runtime.Load(ctx)
    33  	response, handleErr := rt.Endpoints().Request(
    34  		ctx,
    35  		endpointName, listFnName,
    36  		account,
    37  	)
    38  	if handleErr != nil {
    39  		err = handleErr
    40  		return
    41  	}
    42  	v, err = services.ValueOfResponse[[]Authorization](response)
    43  	if err != nil {
    44  		err = errors.Warning("authorizations: scan encode value failed").WithCause(err)
    45  		return
    46  	}
    47  	return
    48  }
    49  
    50  type listFn struct {
    51  	store TokenStore
    52  }
    53  
    54  func (fn *listFn) Name() string {
    55  	return string(listFnName)
    56  }
    57  
    58  func (fn *listFn) Internal() bool {
    59  	return true
    60  }
    61  
    62  func (fn *listFn) Readonly() bool {
    63  	return false
    64  }
    65  
    66  func (fn *listFn) Handle(ctx services.Request) (v any, err error) {
    67  	account, parmaErr := services.ValueOfParam[Id](ctx.Param())
    68  	if parmaErr != nil {
    69  		err = errors.Warning("authorizations: list failed").WithCause(parmaErr)
    70  		return
    71  	}
    72  	entries, listErr := fn.store.List(ctx, account)
    73  	if listErr != nil {
    74  		err = errors.Warning("authorizations: list failed").WithCause(listErr)
    75  		return
    76  	}
    77  	if len(entries) == 0 {
    78  		return
    79  	}
    80  	validates := make([]Authorization, 0, 1)
    81  	for _, entry := range entries {
    82  		if entry.Validate() {
    83  			validates = append(validates, entry)
    84  		}
    85  	}
    86  	v = validates
    87  	return
    88  }