โ† Integrations

Backend ยท TypeScript

A NestJS service for Vimshottari dasha timelines

NestJS wants dependencies behind providers, so AstroNode becomes an injectable service that reads its key from ConfigService and is used by a controller. The example serves a person's Vimshottari mahadasha timeline and the period running today - two endpoints, one free and one on the Hobby plan.

Updated

How this page was checked: astronode.service.ts was executed with tsx on Node 24 against the in-memory API, with its two @nestjs/* imports swapped for stand-ins (a no-op @Injectable() and a ConfigService with the same get / getOrThrow over process.env) - NestJS itself is not installed on the build machine. The timeline, the lookup and the errors below are that run's output. The module and controller were not run; the .env ordering problem was reproduced with process.loadEnvFile.

Configuration and the module

app.module.ts:

ts
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";

import { AstroNodeService } from "./astronode.service";
import { DashaController } from "./dasha.controller";

@Module({
  imports: [ConfigModule.forRoot({ isGlobal: true })], // loads .env
  controllers: [DashaController],
  providers: [AstroNodeService],
})
export class AppModule {}

ConfigModule.forRoot() reads .env from the project root into process.env (git-ignore it), and isGlobal saves importing ConfigModule again in every feature module that needs the key.

The service

astronode.service.ts:

ts
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";

export interface Birth {
  date: string;
  time: string;
  tz_offset_minutes: number;
  lat: number;
  lng: number;
}

export interface Period {
  lord: string;
  start: string;
  end: string;
  years: number;
}

export class AstroNodeError extends Error {
  constructor(
    readonly status: number,
    readonly code: string,
    message: string,
  ) {
    super(`${code}: ${message}`);
  }
}

@Injectable()
export class AstroNodeService {
  private readonly base: string;
  private readonly key: string;

  constructor(config: ConfigService) {
    this.base = config.get("ASTRONODE_BASE_URL", "https://api.astronode.dev");
    this.key = config.getOrThrow<string>("ASTRONODE_API_KEY");
  }

  /** Mahadasha sequence from birth (free tier). */
  async mahadashas(birth: Birth): Promise<Period[]> {
    const data = await this.post<{ mahadasha: Period[] }>("/v1/dasha/vimshottari", birth);
    return data.mahadasha.map(({ lord, start, end, years }) => ({ lord, start, end, years }));
  }

  /** The chain running at one instant (Hobby plan and up). */
  async runningAt(birth: Birth, at: Date) {
    return this.post<Record<"mahadasha" | "antardasha" | "pratyantar", Period>>("/v1/dasha/lookup", {
      birth_input: birth,
      date: at.toISOString(),
      system: "vimshottari",
    });
  }

  private async post<T>(path: string, body: unknown): Promise<T> {
    const res = await fetch(`${this.base}${path}`, {
      method: "POST",
      headers: { Authorization: `Bearer ${this.key}`, "Content-Type": "application/json" },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(15_000),
    });
    const json = await res.json();
    if (!res.ok) throw new AstroNodeError(res.status, json.error.code, json.error.message);
    return json.data as T;
  }
}

getOrThrow makes a missing key a startup failure: Nest instantiates providers while bootstrapping, so the app refuses to start with Configuration key "ASTRONODE_API_KEY" does not exist instead of serving 401s. The mahadasha array also carries nested antardashas; mahadashas() trims them so the controller's response stays small.

The controller

dasha.controller.ts:

ts
import { BadRequestException, Body, Controller, ForbiddenException, Post } from "@nestjs/common";

import { AstroNodeError, AstroNodeService, type Birth } from "./astronode.service";

function rethrow(err: unknown): never {
  if (err instanceof AstroNodeError && err.status === 400) throw new BadRequestException(err.message);
  if (err instanceof AstroNodeError && err.status === 403) throw new ForbiddenException(err.message);
  throw err;
}

@Controller("dasha")
export class DashaController {
  constructor(private readonly astro: AstroNodeService) {}

  @Post("timeline")
  timeline(@Body() birth: Birth) {
    return this.astro.mahadashas(birth).catch(rethrow);
  }

  @Post("now")
  now(@Body() birth: Birth) {
    return this.astro.runningAt(birth, new Date()).catch(rethrow);
  }
}

Nest turns any thrown value that is not an HttpException into 500 Internal server error, so without rethrow a caller's typo in the birth data looks like your server crashing. The body is forwarded as-is, which means the API's strict birth input does the validation: an extra place field came back as 400 VALIDATION_ERROR. Add a DTO class with ValidationPipe({ whitelist: true }) if you want to strip such fields instead.

New York, 14 Feb 1988, 10:05 (`tz_offset_minutes: -300`)
CallResult
mahadashas() first periodVenus to 24 Jan 2000 (11.94 years left at birth)
mahadashas() today's periodRahu, 24 Jan 2023 to 23 Jan 2041
runningAt(2026-12-05)Rahu / Jupiter / Ketu
Jupiter antardasha6 Oct 2025 to 29 Feb 2028

Timestamps are UTC instants; format them in the user's zone before showing dates near a boundary. Why a few minutes of birth time move these dates: Vimshottari dasha calculation.

The mistake that bites first: reading process.env at the top of a file

It is tempting to write const KEY = process.env.ASTRONODE_API_KEY; at the top of the service file. That line runs when the file is first imported - and app.module.ts imports the service *before* its @Module decorator calls ConfigModule.forRoot(), which is what loads .env. Locally, where the key exists only in .env, the constant is undefined; in production, where the host sets real environment variables, it works. A two-file reproduction printed top-level read: undefined | read at call time: from-dotenv.

  • Read configuration through ConfigService in a constructor, as above, never at module scope.
  • runningAt builds its date with toISOString(). Passing an invalid Date throws RangeError: Invalid time value before any request is made - validate user-supplied dates before they reach the service.
  • POST /v1/dasha/vimshottari is on the Free plan; POST /v1/dasha/lookup needs Hobby. On a Free key, /dasha/now returns 403 PLAN_REQUIRED, which the controller passes on as a 403.

Questions

Which AstroNode endpoints does the NestJS example call?
2 endpoints: Vimshottari Dasha (POST /v1/dasha/vimshottari); Current Dasha Lookup (POST /v1/dasha/lookup).
Was the NestJS code on this page actually run?
astronode.service.ts was executed with tsx on Node 24 against the in-memory API, with its two @nestjs/* imports swapped for stand-ins (a no-op @Injectable() and a ConfigService with the same get / getOrThrow over process.env) - NestJS itself is not installed on the build machine. The timeline, the lookup and the errors below are that run's output. The module and controller were not run; the .env ordering problem was reproduced with process.loadEnvFile.