NestJS Integration Guide

Simple Guide to Add JustCMS Content Management to Your NestJS Application

Getting Started with JustCMS in NestJS

Setting up JustCMS in your NestJS project is straightforward and takes just a few minutes. Let's walk through the installation process step by step.

Installing Required Packages

First, you'll need to install the necessary npm packages. JustCMS integration requires two NestJS packages:

npm install @nestjs/axios @nestjs/config

Setting Up Integration Files

Next, you'll need to add three essential files to your project. Create a new directory called justcms in your source folder and add these files:

interfaces.ts

Contains TypeScript interfaces for API responses

justcms.service.ts

Handles all JustCMS API calls

justcms.module.ts

Configures the JustCMS module

The file structure should look like this:

src/
└── justcms/
    ├── interfaces.ts
    ├── justcms.service.ts
    └── justcms.module.ts

Project Structure

That's all you need to get started! The integration is now ready to be configured. This minimal setup keeps your project clean and organized while providing all the necessary functionality to work with JustCMS.

The integration follows NestJS best practices and provides a type-safe way to interact with JustCMS content. The service wraps all API calls in a single place, making it easy to maintain and update.

Type-Safe

Full TypeScript support for all API responses

Modular

Clean separation of concerns following NestJS patterns

Simple

Minimal setup required to get started

Configuration Options for JustCMS Integration

There are two simple ways to configure JustCMS integration in your NestJS application. You can either use environment variables or configure it directly in your module code. Let's explore both options.

Using Environment Variables

The simplest way to configure JustCMS is by using environment variables. You'll need to set up two key variables in your .env file:

JUST_CMS_TOKEN=YOUR_JUSTCMS_API_TOKEN
JUST_CMS_PROJECT=YOUR_JUSTCMS_PROJECT_ID

Once you've set these variables, make sure to load them in your application by using the @nestjs/config package in your main app module.

Module Configuration

Alternatively, you can configure JustCMS directly in your module code. This approach gives you more control and makes the configuration more explicit:

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { JustCmsModule } from './justcms/justcms.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    JustCmsModule.forRoot({
      token: 'YOUR_JUSTCMS_API_TOKEN',
      projectId: 'YOUR_JUSTCMS_PROJECT_ID',
    }),
  ],
})
export class AppModule {}

Environment Variables

Simple setup using .env file - perfect for different environments

Module Configuration

Direct configuration in code - great for explicit setup and testing

Both configuration methods are equally effective - choose the one that better fits your project's needs. Environment variables are great for managing different environments, while module configuration provides better visibility of your setup directly in the code.

Basic Usage of JustCmsService

Using JustCMS in your NestJS application is straightforward. Once you've set up the integration, you can start fetching content right away. Here's how to use the JustCmsService in your controllers.

Injecting the Service

First, you'll need to inject the JustCmsService into your controller. This gives you access to all the content fetching methods.

import { Controller } from '@nestjs/common';
import { JustCmsService } from './justcms/justcms.service';

@Controller('pages')
export class PagesController {
  constructor(private readonly justCmsService: JustCmsService) {}
}

Creating Basic Endpoints

Let's create some basic endpoints to fetch content from JustCMS. Here's a simple example that shows how to get pages and individual page details.

@Controller('pages')
export class PagesController {
  constructor(private readonly justCmsService: JustCmsService) {}

  @Get()
  async getPages() {
    return this.justCmsService.getPages();
  }

  @Get(':slug')
  async getPageBySlug(@Param('slug') slug: string) {
    return this.justCmsService.getPageBySlug(slug);
  }
}

Simple Integration

Just inject the service and start using it in your controllers

Type-Safe

All methods come with TypeScript support for better development experience

Async/Await

All methods return promises for easy handling of asynchronous operations

Common Usage Examples

Here are some practical examples of how to use JustCmsService in different scenarios:

// Get all blog posts
@Get('blog')
async getBlogPosts() {
  return this.justCmsService.getPages({
    filters: { category: { slug: 'blog' } }
  });
}

// Get main navigation menu
@Get('menu')
async getMainMenu() {
  return this.justCmsService.getMenuById('main-menu');
}

// Get all categories
@Get('categories')
async getCategories() {
  return this.justCmsService.getCategories();
}

That's all you need to start using JustCMS in your NestJS application! The service handles all the API communication, so you can focus on building your application logic.

Available API Methods

JustCMS provides several straightforward methods to fetch your content. Each method is designed to be simple to use while giving you exactly the data you need.

getCategories()

Fetch all content categories

getPages()

Get pages with optional filtering and pagination

getPageBySlug()

Retrieve a specific page by its URL slug

getMenuById()

Get menu structure by its ID

Fetching Categories

The simplest way to get your content categories is using the getCategories() method. It requires no parameters and returns all available categories.

const categories = await justCmsService.getCategories();

Working with Pages

Pages can be fetched in two ways - either getting a list of pages with getPages() or retrieving a specific page using getPageBySlug().

// Get all pages
const allPages = await justCmsService.getPages();

// Get filtered pages
const blogPosts = await justCmsService.getPages({
  filters: { category: { slug: 'blog' } }
});

// Get specific page
const aboutPage = await justCmsService.getPageBySlug('about-us');

Menu Management

To fetch a menu structure, use the getMenuById() method with your menu's unique identifier.

const mainMenu = await justCmsService.getMenuById('main-menu');

Pagination Support

When fetching pages, you can use pagination parameters to manage large content sets:

// Get paginated results
const paginatedPages = await justCmsService.getPages({
  start: 0,
  offset: 10
});

Simple Integration

All methods return typed responses for better TypeScript support

Flexible Filtering

Filter pages by category, use pagination for large datasets

Type Safety

Full TypeScript support ensures reliable code completion

JustCMS Utility Functions

JustCMS provides several useful utility functions that make it easier to work with content blocks, images, and categories. These helper functions are built into the JustCmsService and can save you time when handling common content operations.

Working with Content Block Styles

To check if a content block has a specific style, you can use the isBlockHasStyle function. This is particularly useful when you need to apply different styling or logic based on block styles:

// Check if a block has 'highlight' style
const isHighlighted = justCmsService.isBlockHasStyle(block, 'highlight');

Image Handling Functions

getLargeImageVariant()

Gets the large version of an image, typically the second variant in the image array

getFirstImage()

Retrieves the first image from an image block, useful when working with image galleries

// Get large image variant
const largeImage = justCmsService.getLargeImageVariant(image);

// Get first image from an image block
const firstImage = justCmsService.getFirstImage(imageBlock);

Category Checking

When you need to verify if a page belongs to a specific category, use the hasCategory function. This is particularly helpful for filtering and organizing content:

// Check if page belongs to 'blog' category
const isBlogPost = justCmsService.hasCategory(page, 'blog');

Simple to Use

All utility functions are available directly from the JustCmsService instance

Type-Safe

Functions include TypeScript support for better development experience

Case-Insensitive

Style checking is case-insensitive for more flexible usage

These utility functions are designed to make common content management tasks easier and more efficient. They handle the complexity of content manipulation while providing a clean and simple interface for your application code.