Logo

dev-resources.site

for different kinds of informations.

How to work with CAR files with NestJS

Published at
1/2/2025
Categories
carfile
nft
nestjs
ipfs
Author
burgossrodrigo
Categories
4 categories in total
carfile
open
nft
open
nestjs
open
ipfs
open
Author
14 person written this
burgossrodrigo
open
How to work with CAR files with NestJS

What is a CAR File?

A CAR file is a representation of a set of blocks in a DAG (Directed Acyclic Graph) structure. It's widely used in decentralized storage protocols like IPFS for its ability to store data efficiently while ensuring content addressability via CIDs (Content Identifiers).

Steps to Compact Multiple Files into a CAR File

  1. Prepare the Files
    Convert the files into byte arrays or readable streams.
    Ensure the files are properly labeled with metadata if needed.

  2. Use ipfs-car or nft.storage Tools
    Tools like ipfs-car are libraries to create, manipulate, and encode CAR files.

  3. Create a CAR Encoder
    Use the createFileEncoderStream, createDirectoryEncoderStream, or CAREncoderStream to encode the files into CAR format.

Implementation Example

Hereโ€™s how to implement it in a NestJS service using ipfs-car:

File controller:

import { Controller, Post, UploadedFiles, UseInterceptors } from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { FileService } from './file.service';

@Controller('file')
export class FileController {
  constructor(private readonly fileService: FileService) {}

  @Post('upload-car')
  @UseInterceptors(FilesInterceptor('files'))
  async uploadFiles(@UploadedFiles() files: Express.Multer.File[]) {
    const rootCID = await this.fileService.packFilesIntoCar(files);
    console.log(`Root CID: ${rootCID}`);
    return { rootCID };
  }
}
Enter fullscreen mode Exit fullscreen mode

File Service:

import { Injectable } from '@nestjs/common';
import { Blob } from 'nft.storage';
import { CAREncoderStream } from 'ipfs-car';

@Injectable()
export class FileService {
  constructor() {}

  public async packFilesIntoCar(files: Express.Multer.File[]): Promise<string> {
    let rootCID = '';

    try {
      const blobs = files.map((file) => {
        const fileBytes = new Uint8Array(file.buffer);
        return new Blob([fileBytes], { type: file.mimetype });
      });

      // Start encoding files into CAR format
      const encoder = new CAREncoderStream();

      // Add all files to encoder
      for (const blob of blobs) {
        const fileStream = blob.stream();
        const writer = encoder.getWriter();
        for await (const chunk of fileStream) {
          writer.write(chunk);
        }
        writer.close();
      }

      const rootBlock = await encoder.getRootBlock();
      rootCID = rootBlock.cid.toString();

      return rootCID;
    } catch (error) {
      throw new Error(`Error creating CAR file: ${error.message}`);
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Explanation

File Controller:

Exposes an endpoint to upload files (/upload-car).

  • Intercepts files via FilesInterceptor (Multer middleware).
  • Calls the packFilesIntoCar method from the FileService. File Service:

Converts files to Blob objects.

  • Uses CAREncoderStream to encode files into a CAR file.
  • Returns the root CID of the CAR archive.

CAREncoderStream:

  • Writes file blocks to the CAR archive. Generates a root CID for referencing the CAR file.

Benefits

  • Data Integrity: Each block in the CAR file has its unique CID.
  • Compatibility: CAR files are natively supported in IPFS and Filecoin.
  • Efficiency: Combines multiple files into a single compact archive.

Additional Enhancements

  • Save the CAR file locally: Use Node.js fs module to write the CAR stream into a file.

  • Upload CAR to Decentralized Storage: Integrate with nft.storage, Web3.Storage, or similar APIs.

  • Add Metadata: Include additional metadata like file names, timestamps, or descriptions to make the archive more useful.

nft Article's
30 articles in total
Favicon
Discover Top-Notch Decentralized Finance Exchange Development Services
Favicon
How to work with CAR files with NestJS
Favicon
Claim your NFT Legend boxes on Mint Blockchain
Favicon
Event | Mint Blockchain to Launch NFT Legends Season on January 2, 2025
Favicon
NFTScan 2024 Highlights: Empowering the NFT Landscape via Robust Data Infrastructure
Favicon
๐Ÿ–ผ๏ธ Blockchain NFT, ERC721 From Basics To Production ๐Ÿš€
Favicon
When to Use ERC-721 vs ERC-1155: Choosing the Right NFT Standard
Favicon
In-Depth Analysis of the Current Mint Pass: Ecosystem Value and Benefits
Favicon
Mint Blockchain: Connecting Global Consumers With NFTs๐Ÿ€
Favicon
๐Ÿ”จ Lazy Minting vs Batch Minting: Which One is Right for Your NFT Project?
Favicon
Why ERC-721A is More Cost-Efficient Than ERC-721 for Batch Minting
Favicon
Send Tokens in Bulk with Low Fees and Fast Delivery: The Ultimate Airdrop Tool for 2024
Favicon
Kalp Studio NFT Creator: A Comprehensive Tutorial
Favicon
End-to-End Crypto Token Development Services for Next-Gen Blockchain Projects
Favicon
A Walkthrough of Solidity Custom Errors
Favicon
NFTCON 2024 Journey: Mint Blockchainโ€™s Cutting-Edge Insights and Future Strategy
Favicon
Mint Blockchain Community Gathering: Vol. 2 coming soon!
Favicon
Mint 101: How does Mint Blockchain advance on-chain NFT development?
Favicon
How to Construct an NFT Marketplace: Exploring Varieties, Development Phases, and Future Prospects
Favicon
Beyond Art: The Expanding Horizons of NFT Marketplace Development Company
Favicon
Every Blockchain Developer Must Know About This Scam!
Favicon
One Month of MintSwap Mining: A Celebration of Growth and Community
Favicon
Smart Contract Safety: How to Verify Before You Interact
Favicon
Why and How to Get a Verified Blue Checkmark for Your NFT Collection on NFTScan Site
Favicon
Announcing the Launch of Mint Forest 3.0!
Favicon
NFTScan Site: Elevate Your NFT Project with Premium Blue Checkmark Verification and Powerful Project Management Capabilities
Favicon
Understanding smart contracts for NFT marketplace
Favicon
How to write smart contract for NFT marketplace
Favicon
MintSwap Mining Program Update: Optimized Rewards for Maximum Impact!
Favicon
MintSwap Powering Future of Mint Blockchain: DEX, NFT Marketplace, and More

Featured ones: