Skip to content

Commit

Permalink
feature: add generateEtag function
Browse files Browse the repository at this point in the history
  • Loading branch information
levivilet committed Dec 27, 2024
1 parent 32168f9 commit 5a42779
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { createHash } from 'node:crypto'

export const generateEtag = (content: string): string => {
const hash = createHash('sha1')
hash.update(content)
return `W/"${hash.digest('hex')}"`
}
23 changes: 23 additions & 0 deletions packages/preview-process/test/GenerateEtag.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { expect, test } from '@jest/globals'
import * as GenerateEtag from '../src/parts/GenerateEtag/GenerateEtag.ts'

test('generateEtag - generates weak etag from content', () => {
const content = 'test content'
const etag = GenerateEtag.generateEtag(content)
expect(etag).toMatch(/^W\/"[a-f0-9]+"$/)
})

test('generateEtag - generates different etags for different content', () => {
const content1 = 'content 1'
const content2 = 'content 2'
const etag1 = GenerateEtag.generateEtag(content1)
const etag2 = GenerateEtag.generateEtag(content2)
expect(etag1).not.toBe(etag2)
})

test('generateEtag - generates same etag for same content', () => {
const content = 'same content'
const etag1 = GenerateEtag.generateEtag(content)
const etag2 = GenerateEtag.generateEtag(content)
expect(etag1).toBe(etag2)
})

0 comments on commit 5a42779

Please sign in to comment.