<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Ziad Taha]]></title><description><![CDATA[Ziad Taha]]></description><link>https://ziadtaha.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 25 Nov 2026 11:26:52 GMT</lastBuildDate><atom:link href="https://ziadtaha.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Every response from my API looks the same, and it's two small files: NestJS interceptors in a real project]]></title><description><![CDATA[I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a…]]></description><link>https://ziadtaha.hashnode.dev/every-response-from-my-api-looks-the-same-and-it-s-two-small-files-nestjs-interceptors-in-a-real-project</link><guid isPermaLink="true">https://ziadtaha.hashnode.dev/every-response-from-my-api-looks-the-same-and-it-s-two-small-files-nestjs-interceptors-in-a-real-project</guid><category><![CDATA[nestjs]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[web dev]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Ziad Taha]]></dc:creator><pubDate>Tue, 24 Nov 2026 22:38:59 GMT</pubDate><content:encoded><![CDATA[<p>I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a Python AI service), and it's about the two smallest files in the repo that touch every request: the interceptors.</p>
<h2>The problem they solve</h2>
<p>An API with twenty endpoints drifts. One controller returns the entity, another returns <code>{ message: "ok" }</code>, a third returns whatever the service felt like. The frontend ends up with a different parsing rule per screen, and nobody knows how slow anything is until a user complains.</p>
<p>NestJS's answer is interceptors: code that wraps every handler, sees the request going in and the response going out, and can transform either. FaceMark uses two.</p>
<h2>One response shape for everything</h2>
<pre><code class="language-ts">// src/common/interceptors/transform.interceptor.ts
export interface Response&lt;T&gt; {
  success: boolean;
  data: T;
  timestamp: string;
}

@Injectable()
export class TransformInterceptor&lt;T&gt; implements NestInterceptor&lt;T, Response&lt;T&gt;&gt; {
  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;Response&lt;T&gt;&gt; {
    return next.handle().pipe(
      map((data) =&gt; ({
        success: true,
        data: data || null,
        timestamp: new Date().toISOString(),
      })),
    );
  }
}
</code></pre>
<p>Thirty lines, and every successful response from every endpoint now looks like <code>{ success: true, data: ..., timestamp: ... }</code>. The frontend writes its parsing logic once. <code>next.handle()</code> is the actual controller doing its work; the interceptor just maps over what comes back.</p>
<p>The honest limitation I learned while writing this: it only wraps successful responses. Errors go through the exception filter instead, which is a separate piece with its own shape. So "every response looks the same" really means "every response has a defined shape", and there are two of them.</p>
<h2>Free request timing</h2>
<pre><code class="language-ts">// src/common/interceptors/logging.interceptor.ts
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger('HTTP');

  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {
    const request = context.switchToHttp().getRequest();
    const { method, url, ip } = request;
    const now = Date.now();

    return next.handle().pipe(
      tap((data) =&gt; {
        const response = context.switchToHttp().getResponse();
        this.logger.log(
          `${method} ${url} ${response.statusCode} - ${ip} - ${Date.now() - now}ms`,
        );
      }),
    );
  }
}
</code></pre>
<p>Every request gets one log line: method, URL, status, IP, and milliseconds. No APM tool, no dashboard, no config. When I was tuning the face-recognition call, the one that goes out to the Python service, these lines were how I saw the difference between a 40ms cache hit and a multi-second AI call without touching the endpoints themselves.</p>
<p>That's the real pitch for interceptors as a junior: cross-cutting concerns (logging, shaping, timing) live in one place, and your controllers stay about the business.</p>
<h2>What I'd tell another junior dev</h2>
<p>If you copy-paste response formatting into a second controller, stop and write an interceptor. The second copy is when it becomes a convention; the third is when it becomes a bug farm.</p>
<p><code>tap</code> vs <code>map</code> matters. <code>tap</code> observes (logging), <code>map</code> changes (transform). Mixing them up is the classic first interceptor bug: logging inside a <code>map</code> that forgets to return the data.</p>
<p>Interceptors run outside-in, then inside-out. If you stack two, the first one registered sees the request first and the response last. Worth knowing before you wonder why your log line includes or excludes the transform step.</p>
<p>Everything above is from the real repo.</p>
<hr />
<p>I'm a junior full-stack developer (Angular, NestJS, TypeScript, Python) in Alexandria, Egypt, open to junior roles and freelance work. More posts from this project:</p>
<ul>
<li>Circuit breaker + WAL engine: <a href="https://dev.to/ziadtaha/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-1gcp">https://dev.to/ziadtaha/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-1gcp</a></li>
<li>The NestJS-to-Python boundary: <a href="https://dev.to/ziadtaha/my-nestjs-api-talks-to-a-python-ai-microservice-heres-how-i-keep-the-boundary-honest-with-real-160g">https://dev.to/ziadtaha/my-nestjs-api-talks-to-a-python-ai-microservice-heres-how-i-keep-the-boundary-honest-with-real-160g</a></li>
<li>GitHub: <a href="https://github.com/ZiadtahaM">https://github.com/ZiadtahaM</a></li>
<li>Email: <a href="mailto:ziad.taha3456@gmail.com">ziad.taha3456@gmail.com</a></li>
<li><a href="http://dev.to">dev.to</a>: <a href="https://dev.to/ziadtaha">https://dev.to/ziadtaha</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Every error from my API looks the same too: a global exception filter in NestJS (with real code)]]></title><description><![CDATA[I'm a junior full-stack developer from Alexandria, Egypt. In my last post I showed the interceptor that makes every successful FaceMark response one shape…]]></description><link>https://ziadtaha.hashnode.dev/every-error-from-my-api-looks-the-same-too-a-global-exception-filter-in-nestjs-with-real-code</link><guid isPermaLink="true">https://ziadtaha.hashnode.dev/every-error-from-my-api-looks-the-same-too-a-global-exception-filter-in-nestjs-with-real-code</guid><dc:creator><![CDATA[Ziad Taha]]></dc:creator><pubDate>Tue, 24 Nov 2026 20:15:46 GMT</pubDate><content:encoded><![CDATA[<p>I'm a junior full-stack developer from Alexandria, Egypt. In my last post I showed the interceptor that makes every successful FaceMark response one shape. This is the other half: the global exception filter that makes every failed response one shape too, and decides what clients get to learn from a failure.</p>
<p>FaceMark is my face-recognition attendance project (NestJS API, Python AI service, MySQL). Here's the filter, trimmed:</p>
<pre><code class="language-ts">// src/common/filters/http-exception.filter.ts
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse&lt;Response&gt;();
    const request = ctx.getRequest&lt;Request&gt;();

    let status = exception instanceof HttpException
      ? exception.getStatus()
      : HttpStatus.INTERNAL_SERVER_ERROR;

    // TypeORM database errors get their own treatment
    if (exception instanceof QueryFailedError) {
      status = HttpStatus.BAD_REQUEST;
      message = {
        message: 'Database operation failed: An integrity constraint or data format issue occurred.',
        hint: 'Check for duplicate entries or missing required fields.',
        code: (exception as any).code,
        statusCode: status,
      };
    }

    console.error(`[Error] ${request.method} ${request.url}`, exception);

    const isDevelopment = process.env.NODE_ENV === 'development';

    response.status(status).json({
      success: false,
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      error: typeof message === 'string' ? { message } : message,
      stack: isDevelopment ? (exception instanceof Error ? exception.stack : null) : undefined,
    });
  }
}
</code></pre>
<h2>The decisions inside it</h2>
<p>Three error families, three treatments. Known HTTP exceptions (my own <code>throw new ForbiddenException(...)</code>) keep their status and message, because those messages were written for clients. TypeORM's <code>QueryFailedError</code> (duplicate emails, bad foreign keys) becomes a 400 with a safe hint instead of the raw SQL error. Everything unknown becomes a 500 with "Internal server error" and nothing else.</p>
<p>The client never sees a stack trace in production. The <code>isDevelopment</code> check means I get full stacks while building, and clients get a clean shape in production. Stack traces tell attackers which framework, ORM and file layout you run. This one ternary is the cheapest security win in the file.</p>
<p>The log and the response are different audiences. <code>console.error</code> gets the full exception for me; the response gets the shaped version for the client. Beginner-me wrote these as the same thing. They are not.</p>
<h2>How it pairs with the interceptor</h2>
<p>The transform interceptor wraps successes as <code>{ success: true, data, timestamp }</code>. This filter wraps failures as <code>{ success: false, statusCode, timestamp, path, error }</code>. Between the two, the frontend has exactly two response shapes to handle, forever. When I add endpoint number thirty, it changes nothing on the client.</p>
<h2>What I'd tell another junior dev</h2>
<p>Write the error shape before you need it. The first time a duplicate-email signup returns raw SQL to the browser, you'll wish this file existed.</p>
<p>Classify, don't just catch. <code>@Catch()</code> with no argument catches everything; the value is in the <code>instanceof</code> checks that give each family the right status and a safe message.</p>
<p>Your errors are a data leak or a feature. A 403 that says "your role 'student' can't access this, required: [admin, staff]" (my roles guard does exactly this) tells the legitimate caller what to ask for. A raw 500 with a stack trace tells an attacker what to attack.</p>
<p>Everything above is from the real repo.</p>
<hr />
<p>I'm a junior full-stack developer (Angular, NestJS, TypeScript, Python) in Alexandria, Egypt, open to junior roles and freelance work. More posts from this project:</p>
<ul>
<li>Circuit breaker + WAL engine: <a href="https://dev.to/ziadtaha/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-1gcp">https://dev.to/ziadtaha/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-1gcp</a></li>
<li>The NestJS-to-Python boundary: <a href="https://dev.to/ziadtaha/my-nestjs-api-talks-to-a-python-ai-microservice-heres-how-i-keep-the-boundary-honest-with-real-160g">https://dev.to/ziadtaha/my-nestjs-api-talks-to-a-python-ai-microservice-heres-how-i-keep-the-boundary-honest-with-real-160g</a></li>
<li>GitHub: <a href="https://github.com/ZiadtahaM">https://github.com/ZiadtahaM</a></li>
<li>Email: <a href="mailto:ziad.taha3456@gmail.com">ziad.taha3456@gmail.com</a></li>
<li><a href="http://dev.to">dev.to</a>: <a href="https://dev.to/ziadtaha">https://dev.to/ziadtaha</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Keeping students out of staff endpoints: NestJS guards and roles in my attendance project]]></title><description><![CDATA[I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a…]]></description><link>https://ziadtaha.hashnode.dev/keeping-students-out-of-staff-endpoints-nestjs-guards-and-roles-in-my-attendance-project</link><guid isPermaLink="true">https://ziadtaha.hashnode.dev/keeping-students-out-of-staff-endpoints-nestjs-guards-and-roles-in-my-attendance-project</guid><dc:creator><![CDATA[Ziad Taha]]></dc:creator><pubDate>Tue, 24 Nov 2026 20:08:20 GMT</pubDate><content:encoded><![CDATA[<p>I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a Python AI service). This one covers authorization: how the API decides that a student can see their own attendance but nobody else's, and that only staff and admins can pull class-wide records.</p>
<p>FaceMark has three roles, defined as a plain enum:</p>
<pre><code class="language-ts">// src/common/enums/role.enum.ts
export enum Role {
  ADMIN = 'admin',
  STAFF = 'staff',
  STUDENT = 'student',
}
</code></pre>
<p>The system is three small pieces: a JWT guard that answers "who are you", a decorator that answers "who is allowed here", and a roles guard that compares the two.</p>
<h2>The JWT guard</h2>
<pre><code class="language-ts">// src/auth/guards/jwt-auth.guard.ts
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
</code></pre>
<p>That's the whole file. It extends Passport's JWT AuthGuard: no valid token, no request. When the token is valid, the JWT strategy attaches the user (including their role) to the request object. The next piece reads <code>request.user</code>.</p>
<h2>The @Roles decorator</h2>
<pre><code class="language-ts">// src/auth/decorators/roles.decorator.ts
export const ROLES_KEY = 'roles';

export const Roles = (...roles: Role[]) =&gt; SetMetadata(ROLES_KEY, roles);
</code></pre>
<p>This does nothing by itself. It attaches metadata to a route: "this endpoint wants ADMIN and STAFF". I like this pattern because the rule sits right where the route is declared. You read the controller and you see the permission, instead of hunting through a config file somewhere else.</p>
<h2>The roles guard</h2>
<pre><code class="language-ts">// src/auth/guards/roles.guard.ts (trimmed)
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.getAllAndOverride&lt;Role[]&gt;(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requiredRoles) {
      return true;
    }

    const { user } = context.switchToHttp().getRequest();

    if (!user) {
      throw new ForbiddenException('Access Denied: No authenticated user found in request.');
    }

    const hasRole = requiredRoles.some((role) =&gt; user.role === role);
    if (!hasRole) {
      throw new ForbiddenException(
        `Access Denied: Your role '${user.role}' does not have permission to access this resource. Required roles: [${requiredRoles.join(', ')}]`
      );
    }
    return true;
  }
}
</code></pre>
<p>Three decisions in there:</p>
<p><code>getAllAndOverride</code> checks the handler first, the class second. A route-level <code>@Roles</code> beats a controller-level one, so I can set a default on the whole controller and override it on the one endpoint that's different.</p>
<p>No metadata means the guard lets the request through. Authentication is still enforced by the JWT guard, so "logged in, any role" is a deliberate state, not a loophole.</p>
<p>The 403 message tells you your role and what was required. When I was testing with tokens from different seed users, this saved me real debugging time.</p>
<h2>On a real controller</h2>
<pre><code class="language-ts">// src/attendance/controller/attendance.controller.ts (trimmed)
@UseGuards(JwtAuthGuard, RolesGuard)
@Controller('attendance')
export class AttendanceController {

  @Get('my')
  @Roles(Role.STUDENT)
  async getMyAttendance(/* ... */) { /* student's own history */ }

  @Get('course/:courseId')
  @Roles(Role.ADMIN, Role.STAFF)
  async getByCourse(/* ... */) { /* class-wide records */ }

  @Get('track/:studentId')
  @Roles(Role.ADMIN, Role.STAFF)
  async trackStudent(/* ... */) { /* risk analysis for one student */ }
}
</code></pre>
<p>The order in <code>@UseGuards(JwtAuthGuard, RolesGuard)</code> matters. NestJS runs guards left to right, so the JWT guard fills <code>request.user</code> before the roles guard reads it. Get the order wrong and the roles guard sees no user and rejects everything. That was a confusing first bug to hit.</p>
<p>A student calling <code>GET /attendance/my</code> passes both guards and gets exactly their own records. The same student calling <code>GET /attendance/course/3</code> gets a 403. Staff and admin pass both.</p>
<h2>What I'd tell another junior dev</h2>
<p>Authentication and authorization are separate questions. "Who are you" (JWT guard) and "are you allowed" (roles guard) live in different classes here, so either one can change without touching the other.</p>
<p>Put the permission next to the route. <code>@Roles(Role.ADMIN, Role.STAFF)</code> above the handler is documentation that can't drift out of date the way a wiki page does.</p>
<p>Use enums, not strings. Every role reference goes through the <code>Role</code> enum, so a typo is a compile error instead of a string that never matches at runtime.</p>
<p>Everything above is from the real repo, and you can read the full files there.</p>
<hr />
<p>I'm a junior full-stack developer (Angular, NestJS, TypeScript, Python) in Alexandria, Egypt, open to junior roles and freelance work. More posts from this project:</p>
<ul>
<li>Circuit breaker + WAL engine: <a href="https://dev.to/ziadtaha/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-1gcp">https://dev.to/ziadtaha/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-1gcp</a></li>
<li>The NestJS-to-Python boundary: <a href="https://dev.to/ziadtaha/my-nestjs-api-talks-to-a-python-ai-microservice-heres-how-i-keep-the-boundary-honest-with-real-160g">https://dev.to/ziadtaha/my-nestjs-api-talks-to-a-python-ai-microservice-heres-how-i-keep-the-boundary-honest-with-real-160g</a></li>
<li>GitHub: <a href="https://github.com/ZiadtahaM">https://github.com/ZiadtahaM</a></li>
<li>Email: <a href="mailto:ziad.taha3456@gmail.com">ziad.taha3456@gmail.com</a></li>
<li><a href="http://dev.to">dev.to</a>: <a href="https://dev.to/ziadtaha">https://dev.to/ziadtaha</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[My NestJS API Talks to a Python AI Microservice. Here's How I Keep the Boundary Honest (With Real Code)]]></title><description><![CDATA[FaceMark, my face-recognition attendance project, is really two systems that happen to share an HTTP connection: a NestJS API (auth, users, courses…]]></description><link>https://ziadtaha.hashnode.dev/my-nestjs-api-talks-to-a-python-ai-microservice-here-s-how-i-keep-the-boundary-honest-with-real-code</link><guid isPermaLink="true">https://ziadtaha.hashnode.dev/my-nestjs-api-talks-to-a-python-ai-microservice-here-s-how-i-keep-the-boundary-honest-with-real-code</guid><dc:creator><![CDATA[Ziad Taha]]></dc:creator><pubDate>Tue, 24 Nov 2026 14:36:19 GMT</pubDate><content:encoded><![CDATA[<p>FaceMark, my face-recognition attendance project, is really two systems that happen to share an HTTP connection: a NestJS API (auth, users, courses, attendance records, MySQL) and a Python FastAPI service that runs DeepFace and TensorFlow for the actual face recognition.</p>
<p>I wrote both sides. This post is not about face recognition itself. It is about the seam between the two services, because that seam is where every interesting bug in this project has come from. Everything below is real code from the repo: <a href="https://github.com/ZiadtahaM/FaceMark">github.com/ZiadtahaM/FaceMark</a></p>
<h2>The problem with the seam</h2>
<p>Two languages means two naming conventions (TypeScript wants <code>imagesBase64</code>, Python wants <code>images_base64</code>), two error cultures, and two very different failure modes. The NestJS side fails in milliseconds with clean exceptions. The Python side fails slowly, sometimes after 25 seconds of TensorFlow having opinions.</p>
<p>If you let that leak through to your API consumers, your clean REST API starts returning raw Axios errors and Python tracebacks. So the rule I set for myself: nothing crosses the seam unvalidated, and no error crosses it untranslated.</p>
<h2>A typed contract for the Python response</h2>
<p>The AI service returns JSON. "Returns JSON" is not a contract, so the NestJS side defines one with class-validator DTOs:</p>
<pre><code class="language-typescript">export class FaceEmbeddingDto {
  @ApiProperty({ description: 'Face embedding vector', type: [Number] })
  @IsArray()
  @IsNumber({}, { each: true })
  embedding: number[];

  @ApiProperty({ description: 'Index of the image in the batch', example: 0 })
  @IsNumber()
  imageIndex: number;

  @ApiProperty({ description: 'Confidence score', example: 0.95 })
  @IsNumber()
  @Min(0)
  @Max(1)
  confidence: number;
}

export class Model1ResponseDto {
  @IsString()
  studentId: string;

  @IsOptional()
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() =&gt; FaceEmbeddingDto)
  embeddings?: FaceEmbeddingDto[];

  @IsNumber()
  imagesProcessed: number;

  @IsNumber()
  facesDetected: number;

  @IsString()
  versionOfModel: string;
  // ...
}
</code></pre>
<p>The embedding vector is <code>number[]</code> with <code>@IsNumber({}, { each: true })</code>, confidence is bounded <code>@Min(0) @Max(1)</code>, and recognition outcomes are an enum (<code>MATCH</code>, <code>NO_MATCH</code>, <code>NO_FACE_DETECTED</code>, <code>MULTIPLE_FACES</code>) instead of free-form strings. If Python ever sends something else, the failure is mine to handle, in one place, not a surprise three functions later.</p>
<p>The <code>@ApiProperty</code> decorators double as Swagger documentation, so the same DTOs that validate the boundary also document it.</p>
<h2>Translating failures, not forwarding them</h2>
<p>The actual call to the AI service goes through three layers of defense in <code>VisionService.registerStudent</code>:</p>
<pre><code class="language-typescript">// 1. Is the AI service even there?
let healthCheck;
try {
  healthCheck = await firstValueFrom(
    this.httpService.get(`${this.aiServiceUrl}/health`)
  );
} catch (error) {
  healthCheck = null;
}
if (!healthCheck) {
  throw new BadGatewayException('AI service is not running. Please start the FastAPI server on port 8000');
}

// 2. The call itself, guarded by a circuit breaker
const response = await this.circuitBreaker.execute(() =&gt;
  firstValueFrom(
    this.httpService.post(`${this.aiServiceUrl}/upload/batch`, {
      images_base64: dto.imagesBase64,   // camelCase in, snake_case out
      student_id: dto.studentId,
      name: dto.name,
      confidence_threshold: dto.confidenceThreshold || 0.6,
    }, { timeout: 25000 })
  )
);

// 3. The response gets checked before anyone trusts it
const aiResponse: Model1ResponseDto = response.data;
if (!aiResponse.embedding &amp;&amp; !aiResponse.embeddings) {
  throw new BadGatewayException('AI service failed to generate embedding');
}
</code></pre>
<p>Note the naming translation right in the request body: my API speaks camelCase, FastAPI speaks snake_case, and the mapping happens explicitly at the boundary instead of forcing one side's convention on the other.</p>
<p>The error handling has my favorite small decision in the whole project. When the AI processes images but finds no faces, that is not an exception, it is a result:</p>
<pre><code class="language-typescript">if (aiResponse.facesDetected === 0) {
  return {
    studentId: dto.studentId,
    totalImages: dto.imagesBase64.length,
    successfulImages: 0,
    failedImages: dto.imagesBase64.length,
    status: 'FAILED',
    message: 'No faces detected in any of the uploaded images. Please provide clear face images.'
  };
}
</code></pre>
<p>The user gets a sentence they can act on. Meanwhile real failures still become proper HTTP errors: <code>NotFoundException</code> when the student does not exist in MySQL, <code>BadGatewayException</code> when the AI service is the problem. And the catch-all deliberately re-throws the specific exceptions first, so a 404 never gets rewritten into a 502:</p>
<pre><code class="language-typescript">} catch (error) {
  if (error instanceof NotFoundException || error instanceof BadGatewayException) throw error;
  this.logger.error(`[Model 1] Error registering student ${dto.studentId}: ${error.message}`);
  throw new BadGatewayException(`AI service error: ${error.message}`);
}
</code></pre>
<h2>Who is allowed to touch the seam</h2>
<p>Both vision endpoints sit behind two guards and a roles decorator:</p>
<pre><code class="language-typescript">@Post('recognize')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMIN, Role.STAFF)
@ApiOperation({
  summary: 'Model 2: Process camera frame for recognition and automated attendance',
})
@ApiResponse({ status: 200, description: 'Face processed successfully' })
@ApiResponse({ status: 503, description: 'AI service not available' })
async recognize(@Body() dto: ProcessFrameDto, @CurrentUser() user: UserAccount) {
  return this.visionService.processAttendanceFrame(dto);
}
</code></pre>
<p>Face data is sensitive. Students never call these endpoints; only ADMIN and STAFF roles do, with a JWT. The Swagger decorators mean the docs reflect the same contract the guards enforce.</p>
<h2>What I would do differently now</h2>
<ul>
<li><code>registerMultipleStudents</code> <strong>returns</strong> <code>Promise&lt;any[]&gt;</code><strong>.</strong> That <code>any</code> is me breaking my own rule at the bulk boundary. It needs a real DTO.</li>
<li><strong>Contract tests.</strong> The DTOs describe the contract, but nothing automatically verifies the Python side still honors it. A small test suite that replays recorded AI responses against these DTOs would catch drift.</li>
<li><strong>A generated client.</strong> Hand-writing <code>images_base64</code> mappings does not scale past a few endpoints. Generating the NestJS client from the FastAPI OpenAPI schema would make the translation mechanical.</li>
</ul>
<h2>If you need this kind of work</h2>
<p>I build NestJS APIs, Python microservices, and the unglamorous glue between them: validation, error translation, guards, docs. I am a junior developer in Alexandria, Egypt, priced accordingly, and everything above is real code I can walk you through line by line.</p>
<ul>
<li>GitHub: <a href="https://github.com/ZiadtahaM">github.com/ZiadtahaM</a></li>
<li>Email: <a href="mailto:ziad.taha3456@gmail.com">ziad.taha3456@gmail.com</a></li>
<li>More writing on my <a href="https://dev.to/ziadtaha">dev.to profile</a></li>
</ul>
<p>If you are also gluing TypeScript to Python and your errors currently look like <code>AxiosError: Request failed with status code 500</code>, I hope this helps.</p>
]]></content:encoded></item><item><title><![CDATA[I Built an Angular 17 SSR Storefront on a Third-Party API. Here's What SSR Actually Changes (With Real Code)]]></title><description><![CDATA[I'm a junior full-stack developer from Alexandria, Egypt, and one of the bigger projects on my GitHub is an e-commerce storefront built with Angular 17 and…]]></description><link>https://ziadtaha.hashnode.dev/i-built-an-angular-17-ssr-storefront-on-a-third-party-api-here-s-what-ssr-actually-changes-with-real-code</link><guid isPermaLink="true">https://ziadtaha.hashnode.dev/i-built-an-angular-17-ssr-storefront-on-a-third-party-api-here-s-what-ssr-actually-changes-with-real-code</guid><dc:creator><![CDATA[Ziad Taha]]></dc:creator><pubDate>Tue, 24 Nov 2026 14:32:52 GMT</pubDate><content:encoded><![CDATA[<p>I'm a junior full-stack developer from Alexandria, Egypt, and one of the bigger projects on my GitHub is an e-commerce storefront built with Angular 17 and server-side rendering. To be clear about scope up front: I did not build the backend. The app consumes RouteMisr's external e-commerce API for products, brands, categories, cart, wishlist, orders and auth. My job was everything on the client: the Angular app, the SSR setup, the routing, the guards, the UI.</p>
<p>That turned out to be more than enough work. This post is about the parts of Angular SSR that actually bit me, with the real code. The repo is public: <a href="https://github.com/ZiadtahaM/ecommerce-fullstack-app">github.com/ZiadtahaM/ecommerce-fullstack-app</a></p>
<h2>Why SSR for a storefront</h2>
<p>A storefront lives or dies on its product and category pages. With a pure client-rendered Angular app, the first response is an empty shell and a big JavaScript bundle. With SSR (Angular 17 ships <code>@angular/ssr</code> with an Express server), the server renders the page to HTML first, so the user sees real content immediately and the page exists as markup before any JavaScript runs.</p>
<p>What I didn't expect: SSR changes the rules for code you've written a hundred times. Anything that touches the browser, <code>localStorage</code>, <code>window</code>, <code>document</code>, now runs in two environments, and one of them doesn't have those things.</p>
<h2>The localStorage trap, in my own guards</h2>
<p>My app has two route guards. One protects the shop pages (<code>authGuard</code>), one protects the login/register pages (<code>aynelaGuard</code>, sends you to <code>/home</code> if you're already logged in). Both need to read the JWT from <code>localStorage</code>. Both had to learn that the server has no <code>localStorage</code>.</p>
<p>Here's the real <code>authGuard</code> from the repo:</p>
<pre><code class="language-typescript">import { isPlatformBrowser } from '@angular/common';
import { inject, PLATFORM_ID } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';

export const authGuard: CanActivateFn = (route, state) =&gt; {
  const _Router = inject(Router);
  const _PLATFORM_ID = inject(PLATFORM_ID);
  if (isPlatformBrowser(_PLATFORM_ID)) {
    if (localStorage.getItem('usertoken') !== null) {
      return true;
    } else {
      _Router.navigate(['/login']);
      return false;
    }
  } else { return false }
};
</code></pre>
<p>Two things are going on here:</p>
<ol>
<li><code>isPlatformBrowser(PLATFORM_ID)</code> is how you ask "am I in a browser right now?" Without that check, the guard crashes on the server with <code>localStorage is not defined</code>.</li>
<li>Notice the <code>else { return false }</code>. On the server, this guard always refuses. That's a deliberate trade: the server-rendered HTML for a protected page is effectively "nothing yet", and the real check happens once the app hydrates in the browser where the token actually lives. Your auth model decides your rendering model. A token in <code>localStorage</code> is invisible to the server by definition.</li>
</ol>
<p>The funny part: my other guard solves the same problem a different way, with <code>typeof localStorage !== 'undefined'</code> instead of <code>isPlatformBrowser</code>. Both work. Having both in one codebase is a small honest artifact of learning the pattern while building: I wrote one, hit the error, learned the idiomatic version, and never went back to unify them.</p>
<h2>Two layouts, one app</h2>
<p>The routing is split into two shells:</p>
<pre><code class="language-typescript">export const routes: Routes = [
  { path: '', component: AuthLayoutComponent, canActivate: [aynelaGuard], children: [
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent },
    { path: 'register', component: RegisterComponent },
  ]},
  { path: '', component: BlankLayoutComponent, canActivate: [authGuard], children: [
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'products', component: ProductsComponent },
    { path: 'brands', component: BrandsComponent },
    { path: 'categories', component: CategoriesComponent },
    { path: 'cart', component: CartComponent },
    { path: 'wish-list', component: WishListComponent },
    { path: 'details/:id', component: DetailsComponent },
    { path: 'orders/:id', component: OrdersComponent },
    { path: 'allorders', component: AllordersComponent },
    // ...
  ]},
  { path: '**', component: NotfoundComponent }
];
</code></pre>
<p>Two empty paths, two layouts, each with its own guard. The auth pages get one header/footer, the shop gets another, and the guards decide which shell you're even allowed to see. Simple once you see it, but it took me a while to realize <code>path: ''</code> can appear twice as long as the components differ.</p>
<h2>The rest of the stack, briefly</h2>
<ul>
<li><strong>UI:</strong> Angular Material + PrimeNG + Flowbite, with <code>ngx-owl-carousel-o</code> for product carousels. In hindsight three component libraries is too many; that's what tutorials do to you.</li>
<li><strong>Auth token:</strong> the API returns a JWT, stored in <code>localStorage</code>, read client-side with <code>jwt-decode</code>.</li>
<li><strong>Forms:</strong> reactive forms with <code>@rxweb/reactive-form-validators</code> for the validation rules.</li>
</ul>
<h2>What I'd do differently now</h2>
<ul>
<li><strong>One UI library</strong>, not three. The bundle and the CSS conflicts aren't worth it.</li>
<li><strong>HttpOnly cookies or an interceptor-first design</strong> for the token, so SSR can participate in auth instead of being locked out of it.</li>
<li><strong>Tests.</strong> <code>app.component.spec.ts</code> exists; that is nearly the whole test suite, and I know it.</li>
<li><strong>Unify the two guard patterns</strong> into one <code>isPlatformBrowser</code> helper.</li>
</ul>
<h2>If you're hiring or need a frontend built</h2>
<p>I'm available for freelance work: Angular frontends, NestJS APIs, or fixing the SSR bug that's been ruining your week. I'm junior and I price accordingly, but everything above is real code I wrote and can walk you through.</p>
<ul>
<li>GitHub: <a href="https://github.com/ZiadtahaM">github.com/ZiadtahaM</a></li>
<li>Email: <a href="mailto:ziad.taha3456@gmail.com">ziad.taha3456@gmail.com</a></li>
<li>More writing here on my <a href="https://dev.to/ziadtaha">dev.to profile</a></li>
</ul>
<p>Thanks for reading. If you've fought the <code>localStorage is not defined</code> battle on the server, you have my sympathy.</p>
]]></content:encoded></item><item><title><![CDATA[I Wrote a Circuit Breaker and a Bitcask-Style WAL Engine for My Face Recognition API (With Real Code)]]></title><description><![CDATA[A few weeks ago I shared what I learned building FaceMark, my facial-recognition attendance system (a NestJS API + a Python AI service). This post is the…]]></description><link>https://ziadtaha.hashnode.dev/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-code</link><guid isPermaLink="true">https://ziadtaha.hashnode.dev/i-wrote-a-circuit-breaker-and-a-bitcask-style-wal-engine-for-my-face-recognition-api-with-real-code</guid><category><![CDATA[nestjs]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Python]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Ziad Taha]]></dc:creator><pubDate>Tue, 24 Nov 2026 00:09:43 GMT</pubDate><content:encoded><![CDATA[<p>A few weeks ago I shared what I learned building FaceMark, my facial-recognition attendance system (a NestJS API + a Python AI service). This post is the technical deep-dive I promised myself I'd write: the two components I built from scratch instead of pulling in a library, why I built them, and how they actually work.</p>
<p>Everything below is running code from the repo: <a href="https://github.com/ZiadtahaM/FaceMark">ZiadtahaM/FaceMark</a>.</p>
<h2>Why build these myself?</h2>
<p>Two reasons. First, both solve failure modes this architecture genuinely has: the AI service is slow to start and can hang (TensorFlow is heavy), and face embeddings were originally stored as a single pickle file, one bad shutdown away from losing every enrolled face. Second, I'm a junior developer, and I wanted to understand the patterns, not just import them. Both designs are straight out of <em>Designing Data-Intensive Applications</em> (Kleppmann) - the circuit breaker from the reliability chapters and the storage engine from Chapter 3's Bitcask model.</p>
<h2>Component 1: The circuit breaker (TypeScript, NestJS)</h2>
<p><code>VisionService</code> calls the FastAPI service over HTTP for every face registration and recognition. When FastAPI hangs, each hanging request holds a connection. Enough of them and the whole API becomes unresponsive - a cascade failure caused by one dependency. That's the scenario this component is designed for.</p>
<p>The breaker has three states:</p>
<pre><code class="language-typescript">export enum CircuitState {
  CLOSED = 'CLOSED',
  OPEN = 'OPEN',
  HALF_OPEN = 'HALF_OPEN',
}
</code></pre>
<p>The <code>execute</code> wrapper does four things: evaluates whether it's time to probe again, fast-fails while OPEN, caps every call with a timeout budget via <code>Promise.race</code>, and records the outcome:</p>
<pre><code class="language-typescript">public async execute&lt;T&gt;(action: () =&gt; Promise&lt;T&gt;, fallback?: () =&gt; Promise&lt;T&gt; | T): Promise&lt;T&gt; {
  this.evaluateState();

  if (this.state === CircuitState.OPEN) {
    this.logger.warn(`[${this.serviceName}] Fast-failing: Circuit is OPEN.`);
    if (fallback) {
      return fallback();
    }
    throw new ServiceUnavailableException(
      `[${this.serviceName}] Service is temporarily unavailable due to upstream instability. Circuit is OPEN.`
    );
  }

  try {
    // Enforce timeout budget capping
    const result = await Promise.race([
      action(),
      new Promise&lt;never&gt;((_, reject) =&gt;
        setTimeout(
          () =&gt; reject(new Error(`[${this.serviceName}] Request timed out after ${this.timeoutMs}ms`)),
          this.timeoutMs
        )
      ),
    ]);

    this.onSuccess();
    return result;
  } catch (error) {
    this.onFailure(error);
    if (fallback) {
      return fallback();
    }
    throw error;
  }
}
</code></pre>
<p>State transitions are driven by counters, not timers:</p>
<pre><code class="language-typescript">private onFailure(error: any): void {
  this.failureCount++;

  if (this.state === CircuitState.HALF_OPEN || this.failureCount &gt;= this.failureThreshold) {
    this.state = CircuitState.OPEN;
    this.lastStateChange = Date.now();
  }
}
</code></pre>
<p>Three consecutive failures trip CLOSED to OPEN. OPEN rejects immediately with a <code>503</code> for 15 seconds, then a single canary request probes the service in HALF_OPEN. If the canary succeeds, <code>failureCount</code> resets and the circuit closes; if it fails, it re-opens instantly (that's the <code>HALF_OPEN ||</code> condition - one failed probe is enough to re-open).</p>
<p>For retries I use exponential backoff with <strong>full jitter</strong> (the AWS Architecture Blog variant):</p>
<pre><code class="language-typescript">/**
 * Exponential backoff with full jitter formula:
 * t = random(0, min(maxBackoffMs, baseMs * 2^attempt))
 */
public static calculateJitterBackoff(attempt: number, baseMs = 500, maxBackoffMs = 8000): number {
  const exponential = Math.min(maxBackoffMs, baseMs * Math.pow(2, attempt));
  return Math.floor(Math.random() * exponential);
}
</code></pre>
<p>Full jitter matters because without it, N clients retrying after a failure all wake up at the same computed times and hit the recovering service in synchronized waves. Randomizing across <code>[0, exponential]</code> spreads the load.</p>
<p><strong>What this gives the system:</strong> if the AI service dies, the API keeps serving auth, courses, and attendance normally, and recognition endpoints return instant 503s instead of hanging until timeout. The fallback hook also lets a caller substitute a degraded response instead of an error.</p>
<h2>Component 2: A Bitcask-style WAL for face embeddings (Python)</h2>
<p>Face embeddings (512-dim vectors from DeepFace/FaceNet512) live in the Python service. My first version pickled a dict to disk. That design has an obvious weakness: if the process dies mid-write, the file can be corrupted and every enrolled face is lost.</p>
<p>So I wrote <code>BitcaskWalEngine</code>, a log-structured append-only store. Every record on disk looks like this:</p>
<pre><code class="language-plaintext">[CRC32: 4B][Timestamp: 8B][Tombstone: 1B][KeyLen: 2B][ValLen: 4B][Key][Value]
</code></pre>
<pre><code class="language-python"># 4 (CRC32) + 8 (Timestamp float) + 1 (Tombstone flag) + 2 (KeyLen) + 4 (ValLen) = 19 bytes
HEADER_FORMAT = "!IdBHI"
HEADER_SIZE = struct.calcsize(HEADER_FORMAT)
</code></pre>
<p>The design has four moving parts:</p>
<ol>
<li><strong>Writes are appends only.</strong> A <code>put</code> serializes the embedding, computes a CRC32 over header + key + value, appends the record, <code>fsync</code>s, then updates the in-memory index. No in-place updates, ever. The last record for a key wins.</li>
<li><strong>An in-memory Keydir</strong> maps each key to <code>(offset, size, timestamp)</code> in the log, so reads are one seek, not a scan. A second in-memory cache holds the vectors themselves for fast similarity search.</li>
<li><strong>Crash recovery is a sequential replay.</strong> On startup the engine scans the log front to back, verifying the CRC32 of every record. A record that fails its CRC (that's the torn write from a mid-write crash) is counted as corrupt and skipped - everything before it survives:</li>
</ol>
<pre><code class="language-python">def _recover(self):
    """Crash-recovery: Rebuilds Keydir and memory cache by scanning WAL sequentially."""
    self._file.seek(0)
    valid_records = 0
    corrupt_records = 0

    while True:
        offset = self._file.tell()
        header_bytes = self._file.read(self.HEADER_SIZE)
        if not header_bytes or len(header_bytes) &lt; self.HEADER_SIZE:
            break

        crc, ts, tombstone, k_len, v_len = struct.unpack(self.HEADER_FORMAT, header_bytes)
        # ... verify CRC, rebuild keydir and cache
</code></pre>
<ol start="4">
<li><strong>Compaction and tombstones.</strong> Deletes write a record with the tombstone flag set rather than removing bytes. A garbage-collection pass eventually rewrites the log keeping only live records, which is how the file stays bounded despite being append-only.</li>
</ol>
<p>There was also a pragmatic piece I enjoyed: the engine auto-migrates the old pickle file into WAL format on first run, so existing data upgrades without a manual step:</p>
<pre><code class="language-python">if not os.path.exists(self.wal_path) and self.legacy_pickle_path and os.path.exists(self.legacy_pickle_path):
    self._migrate_legacy_pickle()
</code></pre>
<p><strong>What this gives the system:</strong> if the AI service is killed mid-write, startup recovery replays the log, keeps every valid record, and reports how many corrupt tail records it skipped. The CRC32 per record is what makes a torn write detectable instead of silent corruption.</p>
<h2>What I'd tell another junior dev</h2>
<ul>
<li><strong>Write the pattern once by hand, then use the library.</strong> I now understand what mature breaker libraries and real LSM-tree storage engines do, because I felt the edge cases myself: the HALF_OPEN re-trip, the torn write, the replay ordering.</li>
<li><strong>Design for the failure mode your architecture actually has.</strong> A slow, stateful Python AI dependency behind an HTTP boundary is exactly where a circuit breaker earns its keep.</li>
<li><strong>CRCs and fsync are the whole point.</strong> A WAL without integrity checks is just a file you append to and hope.</li>
</ul>
<p>Honest caveat: neither component is production-grade. SQLite would replace my WAL with one dependency, and there are mature breaker libraries for NestJS. But as a learning exercise that also made the system genuinely more robust, I'd do it again.</p>
<hr />
<p>I'm a junior full-stack developer (Angular, NestJS, TypeScript, Python) based in Alexandria, Egypt, currently open to <strong>junior roles and freelance work</strong>. If you're hiring, or you spotted something in my code you'd have done differently, I want to hear it:</p>
<ul>
<li>Email: <a href="mailto:ziad.taha3456@gmail.com"><strong>ziad.taha3456@gmail.com</strong></a></li>
<li>GitHub: <a href="https://github.com/ZiadtahaM">github.com/ZiadtahaM</a> - full repo: <a href="https://github.com/ZiadtahaM/FaceMark">FaceMark</a></li>
</ul>
]]></content:encoded></item></channel></rss>