DEV Community

Cover image for getRegistryIndex() function in shadcn-ui/ui source code.
Ramu Narasinga
Ramu Narasinga

Posted on • Updated on

getRegistryIndex() function in shadcn-ui/ui source code.

This article explains how getRegistryIndex() function in shadcn-ui/ui source code works. You will find this function in shadcn-ui/ui source code related to CLI package.

getRegistryIndex:

getRegistryIndex function is called at Line number #68 in add.ts and this is imported at the top of add.ts from registry/index.ts

getRegistryIndex calls another function named fetchRegistry located in the same file registry/index.ts

fetchRegistry:

async function fetchRegistry(paths: string\[\]) {
  try {
    const results = await Promise.all(
    paths.map(async (path) => {
        const response = await fetch(\`${baseUrl}/registry/${path}\`, {
          agent,
        })
        return await response.json()
      })
    )
    return results
  } catch (error) {
    console.log(error)
    throw new Error(\`Failed to fetch registry from ${baseUrl}.\`)
  }
}
Enter fullscreen mode Exit fullscreen mode

This function accepts a parameter named paths which is an array and wraps paths.map in a Promise.all and makes a fetch call inside the map definition for each path.

You might be wondering what the baseUrl contains.

At the top of the file, you will find the below code snippet at this line

const baseUrl = process.env.COMPONENTS_REGISTRY_URL ?? "https://ui.shadcn.com"

Since getRegistryIndex calls fetchRegistry with [“index.json”], the fetch is made to an endpoint that looks like https://ui.shadcn.com/registry/index.json

Get free courses inspired by the best practices used in open source.

About me:


Website: https://ramunarasinga.com/

Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/

Github: https://github.com/Ramu-Narasinga

Email: ramu.narasinga@gmail.com

Learn the best practices used in open source.

References:

  1. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/commands/add.ts#L68
  2. https://github.com/shadcn-ui/ui/blob/main/packages/cli/src/utils/registry/index.ts#L139
  3. https://ui.shadcn.com/registry/index.json

Top comments (0)