Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
0ss committed Jul 28, 2023
0 parents commit a1150be
Show file tree
Hide file tree
Showing 12 changed files with 8,192 additions and 0 deletions.
32 changes: 32 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: CI
on: [push]
jobs:
build:
name: Build, lint, and test on Node ${{ matrix.node }} and ${{ matrix.os }}

runs-on: ${{ matrix.os }}
strategy:
matrix:
node: ['10.x', '12.x', '14.x']
os: [ubuntu-latest, windows-latest, macOS-latest]

steps:
- name: Checkout repo
uses: actions/checkout@v2

- name: Use Node ${{ matrix.node }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node }}

- name: Install deps and build (with cache)
uses: bahmutov/npm-install@v1

- name: Lint
run: yarn lint

- name: Test
run: yarn test --ci --coverage --maxWorkers=2

- name: Build
run: yarn build
12 changes: 12 additions & 0 deletions .github/workflows/size.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
name: size
on: [pull_request]
jobs:
size:
runs-on: ubuntu-latest
env:
CI_JOB_NUMBER: 1
steps:
- uses: actions/checkout@v1
- uses: andresz1/size-limit-action@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*.log
.DS_Store
node_modules
dist
13 changes: 13 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 120,
"overrides": [
{
"files": ["*.ts", "*.mts"],
"options": {
"parser": "typescript"
}
}
]
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Salah

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
92 changes: 92 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#🥷 Mmry

A simple, lightweight, and easy-to-use memory cache library for TypeScript/JavaScript.

## Installation

To install Mmry, use npm or yarn:

```sh
npm install mmry

# or

yarn add mmry
```

## Usage
```ts
import Mmry from 'mmry';

// Create a new instance of the Mmry class with a string type parameter
const cache = new Mmry<string>();

// Add a value to the cache with a TTL of 5 minutes
cache.put('myKey', 'myValue', '5 minutes');

// Retrieve a value from the cache
const value = cache.get('myKey');

// Remove a value from the cache
cache.del('myKey');

// Retrieve all key-value pairs from the cache
const allItems = cache.getAll();

// Remove all values from the cache
cache.clearAll();
```
## Real-world example

Here's an example of how you could use Mmry with the [Express](https://expressjs.com/) web framework:
```ts
import express, { Request, Response } from 'express';
import Mmry from 'mmry';

// Define the types for the data and the cache
type User = {
id: number;
name: string;
};

type Cache = {
users: User[];
};

// Create a new instance of the Mmry class with the Cache type
const cache = new Mmry<Cache>();

const app = express();

app.get('/api/users', async (req: Request, res: Response) => {
const cachedUsers = cache.get('users');

if (cachedUsers) {
// Return cached users
return res.json(cachedUsers);
}

// Fetch users from database
const users = await fetchUsersFromDatabase();

// Cache users for 5 minutes
cache.put('users', users, '5 minutes');

// Return fetched users
res.json(users);
});

async function fetchUsersFromDatabase(): Promise<User[]> {
// Fetch users from database
return [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' },
{ id: 3, name: 'Bob Johnson' },
];
}

app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```

5 changes: 5 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
58 changes: 58 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"version": "0.1.0",
"license": "MIT",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=10"
},
"scripts": {
"start": "tsdx watch",
"build": "tsdx build",
"test": "jest",
"lint": "tsdx lint",
"prepare": "tsdx build",
"size": "size-limit",
"analyze": "size-limit --why"
},
"peerDependencies": {},
"husky": {
"hooks": {
"pre-commit": "tsdx lint"
}
},
"prettier": {
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
},
"name": "mmry",
"author": "Salah",
"module": "dist/mmry.esm.js",
"size-limit": [
{
"path": "dist/mmry.cjs.production.min.js",
"limit": "10 KB"
},
{
"path": "dist/mmry.esm.js",
"limit": "10 KB"
}
],
"devDependencies": {
"@size-limit/preset-small-lib": "^8.2.6",
"husky": "^8.0.3",
"jest": "^29.6.2",
"prettier": "^3.0.0",
"size-limit": "^8.2.6",
"ts-jest": "^29.1.1",
"tsdx": "^0.14.1",
"tslib": "^2.6.1",
"typescript": "^5.1.6"
}
}
94 changes: 94 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
type CacheItemOptions<T> = {
value: T;
timeoutId?: NodeJS.Timeout;
};

class Mmry<T> {
private cache: Map<string, CacheItemOptions<T>> = new Map();

/**
* Adds a value to the cache with a specified TTL.
* @param key The key associated with the value.
* @param value The value to be cached.
* @param ttlString The TTL string in the format "<amount> <unit>", e.g., "5 minutes", "5234 seconds".
*/
public put(key: string, value: T, ttlString?: string): void {
if (!ttlString) {
this.cache.set(key, { value });
return;
}
const ttl = this.parseTTLString(ttlString);
const timeoutId = setTimeout(() => {
this.del(key);
}, ttl);

const cacheItem: CacheItemOptions<T> = {
value,
timeoutId,
};

this.cache.set(key, cacheItem);
}

/**
* Retrieves a value from the cache.
* @param key The key associated with the value.
* @returns The cached value, or undefined if the key does not exist or has expired.
*/
public get(key: string): T | undefined {
const cacheItem = this.cache.get(key);
return cacheItem?.value;
}

/**
* Removes a value from the cache.
* @param key The key associated with the value.
*/
public del(key: string): void {
const cacheItem = this.cache.get(key);
if (cacheItem) {
clearTimeout(cacheItem.timeoutId);
this.cache.delete(key);
}
}
/**
* Retrieves all key-value pairs from the cache.
* @returns An object containing all cached key-value pairs.
*/
public getAll(): { [key: string]: T } {
const allItems: { [key: string]: T } = {};
for (const [key, cacheItem] of this.cache.entries()) {
allItems[key] = cacheItem.value;
}
return allItems;
}
/**
* Removes all values from the cache.
*/
public clearAll(): void {
for (const cacheItem of this.cache.values()) {
clearTimeout(cacheItem.timeoutId);
}
this.cache.clear();
}

/**
* Parses the TTL string into milliseconds.
* @param ttlString The TTL string in the format "<amount> <unit>", e.g., "5 minutes", "5234 seconds".
* @returns The TTL in milliseconds.
*/
private parseTTLString(ttlString: string): number {
const [amount, unit] = ttlString.split(' ');
const ttl = parseInt(amount);

switch (unit.toLowerCase()) {
case 'seconds':
return ttl * 1000;
case 'minutes':
return ttl * 1000 * 60;
default:
throw new Error('Invalid TTL unit');
}
}
}
export default Mmry;

0 comments on commit a1150be

Please sign in to comment.