# Unleash the power!
<!-- Put the link to this slide here so people can follow -->
slide: https://hackmd.io/@as-sa/B1VPhpqXi#/
---
# cloud project (first part)
#### The idea of this application is to store the images in the cloud, put the link of that image in my databases, and then store the content of images in the cache when requested.
#### I can put (capacity, replacement policy, etc.) for the cache
#### The mem-cache should support two cache replacement policies:
* Random Replacement
* Randomly selects a key and discards it to make space when necessary.
* Least Recently Used
* Discards the least recently used keys first.
#### The mem-cache should store its statistics every 5 seconds.
---
# Insert Image Section
---
# cache implementation
## LRUCache Code Explanation
- The code is a simple implementation of a LRUCache.
- The constructor takes in an integer capacity, and the get() method returns -1 if the key does not exist in the map.
- Otherwise, it returns the value of the key
- The put() method sets a new node with the key and value to be inserted into the list, and then adds that new node to the list.
- Finally, it increments size by one after inserting that new node into its place in this list.
- The clear() function removes all nodes from this list so that there is no more data stored within it and then resets size back to 0 as well as clearing out any old data from this map so that there are no more keys or values stored within it either.
[Link Code On GitHub Here](https://link-url-here.org)
```javascript
class LRUCache {
constructor(capacity) {
this.map = {};
this.list = new DoublyLinkedList();
this.capacity = capacity;
this.size = 0;
}
get(key) {
if (!this.map[key]) return -1;
const node = this.map[key];
this.list.move2front(node);
return node.value;
}
put(key, value) {
if (this.map[key]) {
const node = this.map[key];
node.value = value;
this.list.move2front(node);
return;
}
if (this.size === this.capacity) {
const node = this.list.removeLast();
delete this.map[node.key];
this.size--;
}
const newNode = new Node(key, value);
this.list.add(newNode);
this.map[key] = newNode;
this.size++;
}
clear(){
this.map = {};
this.list = new DoublyLinkedList();
this.size = 0;
}
}
```
## Random cache
---
# Get Image Section
- The code starts by importing the checkKeyQuery and getImageQuery functions, which are used to query for a key's hit rate and miss rate.
- The cache is then referenced in order to retrieve the image associated with that key if it exists in the database.
- The function starts by checking if there is an old value stored for this key using checkKeyQuery(key).
- If there isn't, then a 400 error will be returned as per our 404 page not found logic.
- Otherwise, we use getImageQuery(key) to fetch all of the rows associated with that particular key and store them into an array called rows .
- We also store rowCount , which tells us how many images were retrieved from our database when we ran this query.
- Finally, we use cache.put() to save these values so they can be accessed later on without having to run another query again (i.e., caching).
- The code is a function that returns the image of an item in the cache.
[Link Code On GitHub Here](https://link-url-here.org)
```javascript
import { checkKeyQuery, getImageQuery } from '../database/index.js';
import { cache } from '../routes/index.js';
import cookie from "cookies";
const getImage = async (req, res, next) => {
const { key } = req.query;
const cookies = new cookie(req, res);
try {
let hit_rate = cookies.get('hit_rate') ? JSON.parse(cookies.get('hit_rate')) : 0;
let miss_rate = cookies.get('miss_rate') ? JSON.parse(cookies.get('miss_rate')) : 0;
if(cache.get(key) !== -1){
hit_rate = Math.round(100 - (miss_rate / 2));
miss_rate = Math.round(100 - hit_rate);
cookies.set('hit_rate', JSON.stringify(hit_rate));
cookies.set('miss_rate', JSON.stringify(miss_rate));
return res.status(200).json(cache.get(key));
}
const {rowCount: oldKey} = await checkKeyQuery(key);
if (oldKey === 0) {
return res.status(400).json({ message: 'Key does not exist in our records' });
}
const { rows, rowCount } = await getImageQuery(key);
if (rowCount === 0) {
return res.status(404).json({ message: 'Image not found' });
}
const image = rows[0];
cache.put(key, image);
miss_rate = Math.round(100 - (hit_rate / 2));
hit_rate = Math.round(100 - miss_rate);
cookies.set('hit_rate', JSON.stringify(hit_rate));
cookies.set('miss_rate', JSON.stringify(miss_rate));
return res.status(200).json(image);
} catch (error) {
return next(error);
}
};
export default getImage;
```
---
# List Images Section
---
# Cache Configuration Section
* It has a cache object that is used to store images in memory. The cache object can be configured by the user to have different capacities and replacement policies (LRU or Random).
#### How does it do it?
- The router file has a cache object that is used to store images in memory. The cache object can be configured by the user to have different capacities and replacement policies (LRU or Random).
#### What are its inputs and outputs?
- capacity: Number of megabytes that the cache will hold.
- replacePolicy: Replacement policy for when we need to remove an image from the cache because there isn't enough space left in memory; There are two options LRU or random;
- clearCache: Boolean value indicating if we want to clear all images from our current cache before saving new configuration values; This option is useful when you want to change your replacement policy without losing any data stored in your current cahce.
##### Outputs: A JSON response containing message property with success message if everything goes well otherwise error messages as appropriate
[Link Code On GitHub Here](https://link-url-here.org)
---
# Statistics Section
---
### Thank you! :sheep:
{"metaMigratedAt":"2023-06-17T11:58:21.126Z","metaMigratedFrom":"Content","title":"Unleash the power!","breaks":true,"contributors":"[{\"id\":\"decd6497-855c-4396-bf4a-f0fdafefbb1a\",\"add\":8161,\"del\":4414}]"}