|
| 1 | +// Copyright 2021-2024 Buf Technologies, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import { |
| 16 | + create, |
| 17 | + createRegistry, |
| 18 | + toJson as toJsonOriginal, |
| 19 | +} from "@bufbuild/protobuf"; |
| 20 | +import { anyPack, AnySchema, DurationSchema } from "@bufbuild/protobuf/wkt"; |
| 21 | +import { describe, expect, test } from "@jest/globals"; |
| 22 | + |
| 23 | +/* eslint-disable @typescript-eslint/no-unsafe-return,@typescript-eslint/no-explicit-any */ |
| 24 | + |
| 25 | +describe("default registry with custom toJson()", () => { |
| 26 | + // Define you own default registry |
| 27 | + const registry = createRegistry( |
| 28 | + // You can register as many types as you need. In this example, we only |
| 29 | + // register google.protobuf.Duration. |
| 30 | + DurationSchema, |
| 31 | + ); |
| 32 | + |
| 33 | + // Define your own toJson function that uses your default registry |
| 34 | + const toJson: typeof toJsonOriginal = (schema, message, options) => { |
| 35 | + return toJsonOriginal(schema, message, options ?? { registry }) as any; |
| 36 | + }; |
| 37 | + |
| 38 | + test("works as expected", () => { |
| 39 | + // Create a google.protobuf.Any that holds a google.protobuf.Duration |
| 40 | + const duration = create(DurationSchema, { nanos: 123 }); |
| 41 | + const any = anyPack(DurationSchema, duration); |
| 42 | + |
| 43 | + // Serializing to JSON requires a registry that contains google.protobuf.Duration |
| 44 | + const json = toJson(AnySchema, any); |
| 45 | + |
| 46 | + expect(json).toStrictEqual({ |
| 47 | + "@type": "type.googleapis.com/google.protobuf.Duration", |
| 48 | + value: "0.000000123s", |
| 49 | + }); |
| 50 | + }); |
| 51 | +}); |
0 commit comments