Skip to content

Commit a5dae79

Browse files
committed
feat: support dynamic max-age
1 parent 9fa7fd0 commit a5dae79

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

src/cli.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,16 @@ const cliOptions = [
2929
usage: `htttp-server --cors`,
3030
},
3131
{
32-
option: '-dc, --disable-cache',
32+
option: '--disable-cache',
3333
description: 'Disable cache',
3434
defaultValue: false,
35-
usage: `htttp-server -dc`,
35+
usage: `htttp-server --disable-cache`,
36+
},
37+
{
38+
option: '--max-age <maxAge>',
39+
description: 'Set cache max-age',
40+
defaultValue: 5,
41+
usage: `htttp-server --max-age 5`,
3642
},
3743
{
3844
option: '--compress',
@@ -58,6 +64,7 @@ const server = new Server({
5864
dataPosition: opts.data,
5965
cors: JSON.parse(opts.cors),
6066
cache: !JSON.parse(opts.disableCache),
67+
maxAge: Number(opts.maxAge),
6168
compress: JSON.parse(opts.compress),
6269
});
6370
server.start();

src/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export default class Server {
2020
cors: boolean = false;
2121
cache: boolean = true;
2222
compress: boolean = false;
23+
maxAge: number = 5;
2324

2425
constructor(options?: ServerOptions) {
2526
if (options?.port) {
@@ -46,6 +47,9 @@ export default class Server {
4647
if (options?.compress) {
4748
this.compress = true;
4849
}
50+
if (options?.maxAge) {
51+
this.maxAge = options.maxAge;
52+
}
4953
}
5054

5155
start() {
@@ -252,7 +256,7 @@ export default class Server {
252256
const stat = await fs.stat(file);
253257
const etag = `${stat.mtime.getTime ()}-${stat.size}`;
254258
res.setHeader('Etag', etag);
255-
res.setHeader('Cache-Control', 'max-age=10');
259+
res.setHeader('Cache-Control', `max-age=${this.maxAge}`);
256260
const ifNoneMatch = res.req?.headers['if-none-match'];
257261
if (ifNoneMatch && ifNoneMatch === etag) {
258262
res.statusCode = 304;

src/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export interface ServerOptions {
77
cors?: boolean;
88
cache?: boolean;
99
compress?: boolean;
10+
maxAge?: number;
1011
}
1112

1213
export type Res = http.ServerResponse<http.IncomingMessage> & {

0 commit comments

Comments
 (0)