Skip to content

Commit

Permalink
fix: add unique ID to uploaded images
Browse files Browse the repository at this point in the history
If multiple images with the same name are uploaded
their names collide resulting in only the first one
being shown in all instances.

It does this by adding the current timestamp in
base-16 text with `Date.now().toString(16)`

Co-authored-by: Luke <luke@thisis.la>
  • Loading branch information
franknoirot and thisislawatts committed Feb 9, 2022
1 parent 3750c08 commit ad9a288
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
11 changes: 7 additions & 4 deletions packages/cypress/src/support/custom-assertions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,14 @@ const eqHowto = (chaiObj, utils) => {
title,
tags,
})
// note, full cover image meta won't match as uploaded image meta changes

expect(subject.cover_image.name, 'Cover images').to.eq(
expected.cover_image.name,
)
// We want to validate that uploaded filename matches that originally specified
// by the user. The filename will include a timestamp to avoid collisions with
// existing files that have been uploaded.
// Rather than using a RegExp to validate as our fixture specifies the filename
// using a plain, we can break filename into chunks and validate each of those are present.
// note, full cover image meta won't match as uploaded image meta changes
expect(subject.cover_image.name, 'Cover images').to.satisfy(str => expected.cover_image.name.split('.').filter(Boolean).every(chunk => str.includes(chunk)))

expected.steps.forEach((step, index) => {
expect(subject.steps[index], `Have step ${index}`).to.eqHowtoStep(
Expand Down
24 changes: 22 additions & 2 deletions src/components/ImageInput/ImageConverter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export class ImageConverter extends React.Component<IProps, IState> {

private _generateFileMeta(c: File) {
const meta: IConvertedFileMeta = {
name: c.name,
name: addTimestampToFileName(c.name),
photoData: c,
objectUrl: URL.createObjectURL(c),
type: c.type,
Expand Down Expand Up @@ -100,4 +100,24 @@ export class ImageConverter extends React.Component<IProps, IState> {
}
ImageConverter.defaultProps = {
onImgClicked: () => null,
}
}

/** Insert a base-16 timestamp into a file's name and return it
*/
export const addTimestampToFileName = (str: string): string => {
// Return early for malformed input type 🙈
if (typeof str !== 'string') return str

const indexOfDot = str.lastIndexOf('.')

// Return early if the filename doesn't contain an extension
if (indexOfDot <= 0) return str

// inserts "-[current time in base-16]" right before the file type extension
return (
str.slice(0, indexOfDot) +
'-' +
Date.now().toString(16) +
str.slice(indexOfDot)
)
}

0 comments on commit ad9a288

Please sign in to comment.