👀 See Sanity in action: Watch product demo now →

Create a GraphQL Serializer for an Asset of Type File

1 replies
Last updated: Nov 25, 2020
I tried to create a serializer for an asset of type file that is part of a PortableText field, in order to display a download link for the file. This is what works for me, not sure if there are better options, but I couldn’t find a GraphQL way of getting the asset->url (that would have been the GROQ way) into my GatsbyJS site:
import React from 'react'
import css from './downloadableFile.module.scss'

export default ({ node }) => {
  const baseURL = '<https://cdn.sanity.io/files/>'
  const fileName = `${node.file.asset._ref.split('-')[1]}.${node.file.asset._ref.split('-')[2]}`
  const downloadURL = `${baseURL}${process.env.SANITY_PROJECT_ID}/${process.env.SANITY_DATASET}/${fileName}?dl`

  return (
    &lt;div className={css.root}&gt;
      &lt;p&gt;{node.title} &lt;a href={`${downloadURL}`}&gt;Download&lt;/a&gt;&lt;/p&gt;
    &lt;/div&gt;
  )
}
Just in case this helps anyone.
Nov 25, 2020, 10:43 AM
If you’re using a raw field you could consider using resolveReferences. See example in this section https://github.com/sanity-io/gatsby-source-sanity/#raw-fields
You don’t get the same level of control over which references are resolved as with GROQ but it’s a useful option.
Nov 25, 2020, 10:48 AM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.