Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Sichere ProgrammierungFliproom: a room changeover is a content problem(21.09.2026 um 04:10 Uhr)
Sichere ProgrammierungNova Adiutrix: My Second Agent Built My First Project's To-Do List(21.09.2026 um 04:11 Uhr)
Sichere ProgrammierungFliproom: a room changeover is a content problem(21.09.2026 um 04:10 Uhr)
Sichere ProgrammierungNova Adiutrix: My Second Agent Built My First Project's To-Do List(21.09.2026 um 04:11 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

Why !false Broke My API: Building a Polymorphic Follow System in NestJS

Reagiere als Erste:r — dein Feedback zählt!

I'm building RunHop in public — a social + event platform for running races, built on NestJS.

Today I built the Follow module, and the most interesting problem wasn't the polymorphic design — it was a one-line bug in a response interceptor that silently ate boolean values.

The Module: Polymorphic Follows

Users can follow three types of things: other users, organizations, and events. Instead of three separate tables (user_follows, org_follows, event_follows), there's one Follow table with a targetId and targetType enum:

const targetTypeMap: Record<string, TargetType> = {
    USER: TargetType.USER,
    ORGANIZATION: TargetType.ORGANIZATION,
    EVENT: TargetType.EVENT,
};

The trade-off: the database can't enforce foreign keys on targetId because it could point to any of three tables. So validation happens at the application layer:

private async validateTargetExists(targetId: string, targetType: TargetType): Promise<void> {
    let exists: boolean;

    switch (targetType) {
        case TargetType.USER:
            exists = await this.userService.exists(targetId);
            break;
        case TargetType.ORGANIZATION:
            exists = await this.orgService.exists(targetId);
            break;
        case TargetType.EVENT:
            exists = await this.eventService.exists(targetId);
            break;
        default:
            throw new BadRequestException(`Invalid target type: ${targetType}`);
    }

    if (!exists) {
        throw new NotFoundException(`${targetType} not found.`);
    }
}

This makes the Follow module the only Phase 1 module that imports all three other contexts. It validates across boundaries but doesn't understand the internals of any of them — it only calls .exists().

The Bug: !false === true

The isFollowing method checks whether a follow relationship exists and returns a boolean:

async isFollowing(followerId: string, targetId: string, targetType: string) {
    const follow = await this.prismaService.follow.findUnique({
        where: {
            followerId_targetId_targetType: {
                followerId, targetId,
                targetType: targetTypeMap[targetType],
            },
        },
    });

    return !!follow;
}

This returns true or false. Clean. Correct. But the API was returning { data: null } instead of { data: false }.

The culprit was the global TransformInterceptor:

intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
        map((response) => {
            if (!response) {          // <-- this line
                return { data: null };
            }
            if (response.data && response.meta) {
                return response;
            }
            return { data: response };
        }),
    );
}

!false evaluates to true. So when isFollowing returned false, the interceptor treated it as an empty response and replaced it with null.

The fix:

if (response === null || response === undefined) {
    return { data: null };
}

Strict equality. false passes through to return { data: response } and becomes { data: false }.

Route Collisions in NestJS

Another gotcha: I had GET /users/following in the FollowController and GET /users/:id in the UserController. NestJS matched :id first, interpreting "following" as a user ID, and returned a 404 from UserService.findById("following").

Parameterized routes are greedy — :id matches any string. If you have a static route at the same depth, the param route wins if it's registered first. The fix was changing to GET /users/me/following, which has a different shape and doesn't collide.

Worth knowing: GET /users/:id/followers (three segments) doesn't conflict with GET /users/:id (two segments). NestJS only matches routes with the same segment count.

E2E Testing Strategy

The e2e test creates 5 accounts in the first beforeAll, caches them in a listNewAccounts array, and reuses them across four different describe blocks:

let listNewAccounts: ResponseUser[] = [];

// In listFollowing beforeAll:
listNewAccounts.push(newAccount.body.data);

// In listFollowers beforeAll:
for (const newAccount of listNewAccounts) {
    await request(app.getHttpServer())
        .post('/api/v1/follows')
        .set('Authorization', `Bearer ${newAccount.accessToken}`)
        .send({ targetId: targetUser.user.id, targetType: 'USER' });
}

Same 5 accounts follow the target user, then the test org, then the test event. No redundant registrations. The isFollowing tests pick randomly from the cached list to verify both true and false cases.

Takeaway

Falsy coercion in middleware or interceptors is a subtle bug class. !response catches false, 0, and "" along with null and undefined. If your API can legitimately return any falsy value, use strict equality checks. The interceptor worked fine for months because every endpoint returned objects or null — it only broke when isFollowing introduced the first boolean return.

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Why !false Broke My API: Building a Polymorphic Follow System in NestJS

Thematisch verwandte Begriffe: false, Broke, Building, Polymorphic · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-93977 | A vulnerability was determined in code-projects Assessment Management 1.…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick