typescript 51 lines · 8 steps

A cache-aside country lookup in NestJS

A NestJS service resolves country codes by checking the cache first and only hitting the database for the misses.

Explained by highlit
1import { Inject, Injectable, Logger } from '@nestjs/common';
2import { CACHE_MANAGER } from '@nestjs/cache-manager';
3import { Cache } from 'cache-manager';
4import { InjectRepository } from '@nestjs/typeorm';
5import { In, Repository } from 'typeorm';
6import { Country } from './entities/country.entity';
7 
8@Injectable()
9export class CountryLookupService {
10 private readonly logger = new Logger(CountryLookupService.name);
11 private readonly ttl = 60 * 60 * 24;
12 
13 constructor(
14 @Inject(CACHE_MANAGER) private readonly cache: Cache,
15 @InjectRepository(Country) private readonly countries: Repository<Country>,
16 ) {}
17 
18 async getMany(codes: string[]): Promise<Map<string, Country>> {
19 const wanted = [...new Set(codes.map((c) => c.toUpperCase()))];
20 const resolved = new Map<string, Country>();
21 const misses: string[] = [];
22 
23 for (const code of wanted) {
24 const hit = await this.cache.get<Country>(this.key(code));
25 if (hit) resolved.set(code, hit);
26 else misses.push(code);
27 }
28 
29 if (misses.length === 0) return resolved;
30 
31 this.logger.debug(`Loading ${misses.length} countries from DB: ${misses.join(', ')}`);
32 const rows = await this.countries.find({ where: { code: In(misses) } });
33 
34 await Promise.all(
35 rows.map(async (row) => {
36 await this.cache.set(this.key(row.code), row, this.ttl);
37 resolved.set(row.code, row);
38 }),
39 );
40 
41 return resolved;
42 }
43 
44 async invalidate(code: string): Promise<void> {
45 await this.cache.del(this.key(code.toUpperCase()));
46 }
47 
48 private key(code: string): string {
49 return `country:${code}`;
50 }
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The cache-aside pattern reads from cache first and populates it only on a miss, keeping the database as the source of truth.
  2. 2Batching lets you resolve many keys in one database round-trip by querying only the codes that missed the cache.
  3. 3Normalizing and deduplicating inputs up front keeps cache keys consistent and avoids redundant work.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps

Share this explainer

Here's the card — post it anywhere.

A cache-aside country lookup in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code