Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: reproduce issue 2979 #2980

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion examples/example-app-v19/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"@types/node": "^22.13.5",
"jest": "^29.7.0",
"jest-preset-angular": "^14.5.2",
"typescript": "~5.6.2"
"typescript": "~5.6.2",
"zod": "^3.24.2"
}
}
13 changes: 13 additions & 0 deletions examples/example-app-v19/src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { HttpResponse } from '@angular/common/http';
import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { provideRouter, Router, RouterLink } from '@angular/router';
import { z } from 'zod';

import { AppComponent } from './app.component';
import { appConfig } from './app.config';
import { UserService } from './model';
import { serializeResponse } from './response.serializer';

@Component({ selector: 'app-banner', template: '' })
class BannerStubComponent {}
Expand Down Expand Up @@ -83,4 +86,14 @@ function tests() {

expect(TestBed.inject(Router).url).toBe('/heroes');
}));

it('should serialize response', async () => {
const zodSchema = z.object({
name: z.string(),
});

const serializedResponse = await serializeResponse(zodSchema, new HttpResponse({ body: { name: 'test' } }));

expect(serializedResponse.body).toStrictEqual({ name: 'test' });
});
}
49 changes: 49 additions & 0 deletions examples/example-app-v19/src/app/response.serializer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { HttpResponse } from '@angular/common/http';
import { ZodError, ZodObject, ZodTypeAny, z } from 'zod';

export async function serializeResponse<T extends ZodTypeAny>(
zodRef: T,
response: HttpResponse<unknown>,
debug = false,
) {
const { data: body, error } = await serializeResponseBody(zodRef, response.body, debug);

if (error && debug) {
reportSchemaDeviation(error, response);
}

return response.clone({ body });
}

export type SerializeBodyResult<T extends ZodTypeAny> = Promise<{
data: z.infer<T>;
error?: ZodError;
}>;

export async function serializeResponseBody<T extends ZodTypeAny>(
zodRef: T,
body: unknown,
strict = false,
): SerializeBodyResult<T> {
const { data, error, success } =
zodRef instanceof ZodObject
? await (strict ? zodRef.strict().safeParseAsync(body) : zodRef.safeParseAsync(body))
: await zodRef.safeParseAsync(body);

if (success) {
return { data };
}

return { error, data };
}

function reportSchemaDeviation(error: ZodError, response: HttpResponse<unknown>) {
const debug = (msg: string) => console.log(`%c${msg}`, 'color: orange;');

debug('----- [DataAccess] ⚠️ Response schema errors detected (dev mode) -----');
debug(`Request ${response.url}`);
debug(`Response ${response.status} (${response.statusText})`);
console.warn(error.errors);
const { formErrors } = error.flatten();
debug(formErrors.join(','));
}
8 changes: 8 additions & 0 deletions examples/example-app-v19/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5649,6 +5649,7 @@ __metadata:
rxjs: "npm:^7.8.2"
tslib: "npm:^2.8.1"
typescript: "npm:~5.6.2"
zod: "npm:^3.24.2"
zone.js: "npm:~0.15.0"
languageName: unknown
linkType: soft
Expand Down Expand Up @@ -11116,6 +11117,13 @@ __metadata:
languageName: node
linkType: hard

"zod@npm:^3.24.2":
version: 3.24.2
resolution: "zod@npm:3.24.2"
checksum: 10/604c62a8cf8e330d78b106a557f4b44f5d14845d20b1360a423ccc09b58cb8525ccf7e4b40cf1bd4852d22393d2c67774b5817ec5a2fedab25f543b36ed15943
languageName: node
linkType: hard

"zone.js@npm:~0.15.0":
version: 0.15.0
resolution: "zone.js@npm:0.15.0"
Expand Down