github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/services/caches/service.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 caches 19 20 import ( 21 "fmt" 22 "github.com/aacfactory/errors" 23 "github.com/aacfactory/fns/services" 24 ) 25 26 var ( 27 endpointName = []byte("caches") 28 getFnName = []byte("get") 29 setFnName = []byte("set") 30 remFnName = []byte("remove") 31 ) 32 33 func NewWithStore(store Store) services.Service { 34 return &service{ 35 Abstract: services.NewAbstract(string(endpointName), true, store), 36 sn: store.Name(), 37 } 38 } 39 40 // New 41 // use @cache, and param must implement KeyParam. unit of ttl is seconds and default value is 10 seconds. 42 // @cache get 43 // @cache set 10 44 // @cache remove 45 // @cache get-set 10 46 func New() services.Service { 47 return NewWithStore(&defaultStore{}) 48 } 49 50 type service struct { 51 services.Abstract 52 sn string 53 } 54 55 func (s *service) Construct(options services.Options) (err error) { 56 err = s.Abstract.Construct(options) 57 if err != nil { 58 return 59 } 60 c, has := s.Components().Get(s.sn) 61 if !has { 62 err = errors.Warning("fns: caches service construct failed").WithCause(fmt.Errorf("store was not found")) 63 return 64 } 65 store, ok := c.(Store) 66 if !ok { 67 err = errors.Warning("fns: caches service construct failed").WithCause(fmt.Errorf("%s is not store", s.sn)) 68 return 69 } 70 s.AddFunction(&getFn{ 71 store: store, 72 }) 73 s.AddFunction(&setFn{ 74 store: store, 75 }) 76 s.AddFunction(&removeFn{ 77 store: store, 78 }) 79 return 80 }