Skip to content

Commit

Permalink
refactor: Add Shortener class
Browse files Browse the repository at this point in the history
  • Loading branch information
sigfriedCub1990 committed Apr 8, 2023
1 parent 1c35f99 commit 80e49af
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 1 deletion.
53 changes: 53 additions & 0 deletions __tests__/unit/shortener.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import Shortener from '../../lib/shortener';

jest.mock('../../db', () => {
return {
__esModule: true,
default: {
get: jest
.fn()
.mockResolvedValueOnce('https://rsgarxia.is-a.dev')
.mockResolvedValueOnce({
status: 'error',
reason: 'URL not found',
}),
set: jest.fn().mockResolvedValueOnce(true),
},
};
});

describe('Shortener', () => {
describe('urlByHash method', () => {
describe('if Hash exists', () => {
it('returns URL', async () => {
const url = await Shortener.urlByHash('some-uuid');

expect(url).toBe('https://rsgarxia.is-a.dev');
});
});

describe('if Hash does not exist', () => {
it('returns JSON with error message', async () => {
const result = await Shortener.urlByHash('some-uuid');

expect(result).toMatchObject({
reason: expect.any(String),
status: expect.any(String),
});
});
});
});

describe('hashUrl method', () => {
it('returns JSON with URL hash', async () => {
const url = 'https://rsgarxia.is-a.dev';
const hash = await Shortener.hashUrl(url);

expect(hash).toMatchObject({
status: 'success',
original_url: url,
shortened_url: expect.any(String),
});
});
});
});
4 changes: 3 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
verbose: true,
preset: 'ts-jest',
testEnvironment: 'node',
};
testPathIgnorePatterns: ['dist/*', 'node_modules'],
};
29 changes: 29 additions & 0 deletions lib/shortener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import client from '../db';
import mmh3 from 'murmurhash3';

const DOMAIN = process.env.DOMAIN || 'https://frodo.sigfried.xyz';

class Shortener {
static async urlByHash(hash: string) {
const url = await client.get(hash);

return url ? url : { status: 'error', reason: 'URL not found' };
}

static async hashUrl(url: string) {
const hash = mmh3.murmur32HexSync(url);

const maybeKeyValue = await this.urlByHash(hash);
if (!maybeKeyValue) {
await client.set(hash, url);
}

return {
status: 'success',
original_url: url,
shortened_url: `${DOMAIN}/${hash}`,
};
}
}

export default Shortener;

0 comments on commit 80e49af

Please sign in to comment.