Skip to content

Commit

Permalink
feat: Update handler.ts and router.ts for better code structure
Browse files Browse the repository at this point in the history
  • Loading branch information
wajeht committed Jul 28, 2024
1 parent 91707d0 commit f00938f
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 41 deletions.
34 changes: 1 addition & 33 deletions src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function getHealthzHandler() {
};
}

export function getDownloadCommitDotShHandler(
export function getIndexHandler(
fs: typeof import('node:fs/promises'),
cache: CacheType,
commitDotSh: string,
Expand All @@ -32,38 +32,6 @@ export function getDownloadCommitDotShHandler(
};
}

export function getIndexHandler(
fs: typeof import('node:fs/promises'),
cache: CacheType,
commitDotSh: string,
commitDotShPath: string,
extractDomain: (req: Request) => string,
) {
return async (req: Request, res: Response) => {
if (req.get('Content-Type') === 'application/json') {
let file = cache.get(commitDotShPath);

if (!file) {
file = await fs.readFile(commitDotShPath, 'utf-8');
file = file.replace(/http:\/\/localhost/g, extractDomain(req) + '/');
cache.set(commitDotShPath, file);
}

return res
.setHeader('Content-Disposition', `attachment; filename=${commitDotSh}`)
.setHeader('Cache-Control', 'public, max-age=2592000') // Cache for 30 days
.status(200)
.send(file);
}

const domain = extractDomain(req);

const message = `Run this command: 'curl -s ${domain}/${commitDotSh} | sh'`;

return res.status(200).json({ message });
};
}

export function postGenerateCommitMessageHandler(ai: (type?: Provider) => AIService) {
return async (req: GenerateCommitMessageRequest, res: Response) => {
const { diff, provider } = req.body;
Expand Down
8 changes: 0 additions & 8 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { ai } from './ai';
import { cache, extractDomain, getIpAddress } from './util';
import { limitIPsMiddleware, catchAsyncErrorMiddleware } from './middleware';
import {
getDownloadCommitDotShHandler,
postGenerateCommitMessageHandler,
getHealthzHandler,
getIndexHandler,
Expand All @@ -18,13 +17,6 @@ const commitDotShPath = path.resolve(path.join(process.cwd(), 'src', commitDotSh

const router = express.Router();

router.get(
'/commit.sh',
catchAsyncErrorMiddleware(
getDownloadCommitDotShHandler(fs, cache, commitDotSh, commitDotShPath, extractDomain),
),
);

router.get(
'/',
catchAsyncErrorMiddleware(
Expand Down

0 comments on commit f00938f

Please sign in to comment.