1
\$\begingroup\$

I have an attachment uploading feature in my web app.

File can have type- image/png or image/jpg or image/jpeg or application/pdf

For images, I need to return Photo, for pdf Document.

Documents will be only pdf, but images can be extended to images/ico, etc.

Now my code looks like this.

getAttachmentType(attachmentTypeHeader: string): string {
    if (
        attachmentTypeHeader === 'image/png' ||
        attachmentTypeHeader === 'image/jpg' ||
        attachmentTypeHeader === 'image/jpeg'
    ) {
        return 'Photo';
    }
    if (attachmentTypeHeader === 'application/pdf') {
        return 'Document';
    }
}

How I can make it check like image/*?

\$\endgroup\$
  • 1
    \$\begingroup\$ if (attachmentTypeHeader.startsWith('image/')) \$\endgroup\$ – wOxxOm Oct 30 '19 at 11:24
2
\$\begingroup\$

Usually if I have a big list of mappings from one string to another, that is likely to be later enhanced on, I use a generic mapping method, that is fed a static mapping constant.

So the first iteration would be something like:

type ExpectedMimeTypes =
  'image/png' |
  'image/jpg' |
  'image/jpeg' |
  'application/pdf' |
  never;

type ExpectedMagicOutput =
  'Photo' |
  'Document' |
  'Unknown' |
  never;

type MimeTypeMapping = {
  [key in ExpectedMimeTypes]?: ExpectedMagicOutput 
}

const MAP_MIME_TYPE_TO_MAGIC_STRING: MimeTypeMapping = {
  'image/png': 'Photo',
  'image/jpg': 'Photo',
  'image/jpeg': 'Photo',
  'application/pdf': 'Document'
}

function getAttachmentType(attachmentTypeHeader: ExpectedMimeTypes): ExpectedMagicOutput {
  if (attachmentTypeHeader in MAP_MIME_TYPE_TO_MAGIC_STRING) {
    return MAP_MIME_TYPE_TO_MAGIC_STRING[attachmentTypeHeader]!; 
  } else {
    return 'Unknown';
  } 
}

If you are using TypeScript, go all in, meaning be as specific as possible. You do not expect arbitrary string as a result from getAttachmentType() but specific ones. You should explicitly model them, either by using unions or string-based enums. This fosters reusability.

The above solution gives you full type-safety, while being easily enhanced for other types; simply add them to the ExpectedMimeTypes and then you can easily add them to the constant MAP_MIME_TYPE_TO_MAGIC_STRING and vice versa, you cannot add mappings there, that have not been mentioned in the types above.

You could make ExpectedMimeTypes configurable by putting them into a dedicated file and let that be generated via a config and a simple script. That way you get both - configurable mime types and static compile type safety.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.