From b3a9587756c39d11d131306a8da45f19171bfe62 Mon Sep 17 00:00:00 2001 From: Daniel Supernault Date: Tue, 30 Apr 2019 22:40:15 -0600 Subject: [PATCH] Add NotificationService --- app/Services/NotificationService.php | 98 ++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 app/Services/NotificationService.php diff --git a/app/Services/NotificationService.php b/app/Services/NotificationService.php new file mode 100644 index 000000000..91b2d21c7 --- /dev/null +++ b/app/Services/NotificationService.php @@ -0,0 +1,98 @@ + 300 ? 300 : $stop; + $ids = Redis::zrangebyscore($key, $start, $stop); + if(empty($ids)) { + $ids = self::coldGet($id, $start, $stop); + } + foreach($ids as $id) { + $res->push(self::getNotification($id)); + } + return $res; + } + + public static function coldGet($id, $start = 0, $stop = 300) + { + $stop = $stop > 300 ? 300 : $stop; + $ids = Notification::whereProfileId($id) + ->latest() + ->skip($start) + ->take($stop) + ->pluck('id'); + foreach($ids as $key) { + self::set($id, $key); + } + return $ids; + } + + public static function set($id, $val) + { + return Redis::zadd(self::CACHE_KEY . $id, $val, $val); + } + + public static function del($id, $val) + { + return Redis::zrem(self::CACHE_KEY . $id, $val); + } + + public static function add($id, $val) + { + return self::set($id, $val); + } + + public static function rem($id, $val) + { + return self::del($id, $val); + } + + public static function count($id) + { + return Redis::zcount(self::CACHE_KEY . $id, '-inf', '+inf'); + } + + public static function getNotification($id) + { + return Cache::remember('service:notification:'.$id, now()->addDays(7), function() use($id) { + $n = Notification::findOrFail($id); + $fractal = new Fractal\Manager(); + $fractal->setSerializer(new ArraySerializer()); + $resource = new Fractal\Resource\Item($n, new NotificationTransformer()); + return $fractal->createData($resource)->toArray(); + }); + } + + public static function warmCache($id, $stop = 100, $force = false) + { + if(self::count($id) == 0 || $force == true) { + $ids = Notification::whereProfileId($id) + ->latest() + ->limit($stop) + ->pluck('id'); + foreach($ids as $key) { + self::set($id, $key); + } + return 1; + } + return 0; + } +} \ No newline at end of file