Skip to content

Les étapes de la démonstration

Sur cette démonstration, nous verrons comment charger un fichier GraphQL en tant que module Node.js.

Voici les différents fichiers de la démo :

js
import {register} from 'node:module'
import {pathToFileURL} from 'node:url'

register(pathToFileURL(`${import.meta.dirname}/graphql.hook.js`))
js
const extensionsRegex = /\.(graphql|gql|graphqls|gqls)$/

export async function load (url, context, nextLoad) {
  if (extensionsRegex.test(url)) {
    // Load the raw source code.
    const {source: rawSource} = await nextLoad(url, {...context, format: 'module'})

    // Then transform it into a JavaScript module.
    const transformedSource = `export default \`${rawSource.toString()}\``

    return {
      format: 'module',
      shortCircuit: true,
      source: transformedSource
    }
  }

  // Let Node.js handle all other URLs.
  return nextLoad(url)
}
js
import getProductsQuery from './queries/getProducts.graphql'
import {createDirectus, graphql, staticToken} from '@directus/sdk'

const client = createDirectus(process.env.CMS_DIRECTUS_URL).with(staticToken(process.env.CMS_DIRECTUS_TOKEN)).with(graphql())

function getProducts () {
  console.log('Loading products from CMS...')
  return client.query(getProductsQuery)
}

const products = await getProducts()

console.log(products)
graphql
query getAllProducts {
    resorts (filter: {
        status: {
            _eq: "published"
        }
        is_opened: {_eq: true}
    }) {
        id
        uuid
        clubmed_id
        has_dresscode
        has_program
        has_spa
        booker_credentials
        booker_location_id
        translations {
            languages_code {
                code
            }
            title
        }
    }
}

Voir le code complet:

Usage

sh
cd packages/loaders/example
yarn start:esm