azure-sdk-for-js/sdk/schemaregistry/schema-registry-json
Jeremy Meng a28e8f0795 [EngSys] move to vendored version of cross-env via dev-tool
***NO_CI***

- apply the transformation

- update samples' README
2024-11-02 00:48:06 +00:00
..
review [eslint-plugin] add rule "@typescript-eslint/consistent-type-imports": "warn" 2024-10-30 15:48:52 +00:00
samples [EngSys] move to vendored version of cross-env via dev-tool 2024-11-02 00:48:06 +00:00
samples-dev [SR Json and Avro] Samples Fix (#31399) 2024-10-14 15:09:14 -07:00
src [eslint-plugin] add rule "@typescript-eslint/consistent-type-imports": "warn" 2024-10-30 15:48:52 +00:00
test/public [eslint-plugin] add rule "@typescript-eslint/consistent-type-imports": "warn" 2024-10-30 15:48:52 +00:00
.nycrc
CHANGELOG.md Post release automated changes for schemaregistry releases (#31136) 2024-09-17 12:18:27 -07:00
LICENSE
README.md [Schema Registry] Update JsonSchemaSerializer Class Name (#29978) 2024-06-17 15:04:24 -07:00
api-extractor.json
karma.conf.js [Schema Registry] Migrate Test Suite Authentication (#29934) 2024-07-02 12:04:34 -07:00
package.json [EngSys] move to vendored version of cross-env via dev-tool 2024-11-02 00:48:06 +00:00
sample.env [Schema Registry] Migrate Test Suite Authentication (#29934) 2024-07-02 12:04:34 -07:00
tests.yml [Eng] Set Default for Federated Auth to True (#30163) 2024-07-22 17:24:20 -07:00
tsconfig.json [EngSys] upgrade dev dependency `typescript` version to `~5.6.2` 2024-09-19 18:07:31 -07:00

README.md

Azure Schema Registry Json Serializer client library for JavaScript

Azure Schema Registry is a schema repository service hosted by Azure Event Hubs, providing schema storage, versioning, and management. This package provides an Json serializer capable of serializing and deserializing payloads containing Json-serialized data.

Key links:

Getting started

Prerequisites

Install the @azure/schema-registry-json package

Install the Azure Text Analytics client library for JavaScript with npm:

npm install @azure/schema-registry-json

Key concepts

JsonSchemaSerializer

Provides API to serialize to and deserialize from JSON wrapped in a message with a content type field containing the schema ID. Uses SchemaRegistryClient from the @azure/schema-registry package to get schema IDs from schema definition or vice versa. The provided API has internal cache to avoid calling the schema registry service when possible.

Messages

By default, the serializer will create messages structured as follows:

  • data: a byte array containing JSON data.

  • contentType: a string of the following format application/json+<Schema ID> where the application/json part signals that this message has a Json-serialized payload and the <Schema Id> part is the Schema ID the Schema Registry service assigned to the schema used to serialize this payload.

Not all messaging services are supporting the same message structure. To enable integration with such services, the serializer can act on custom message structures by setting the messageAdapter option in the constructor with a corresponding message producer and consumer. Azure messaging client libraries export default adapters for their message types.

Examples

Serialize and deserialize an @azure/event-hubs's EventData

const { DefaultAzureCredential } = require("@azure/identity");
const { createEventDataAdapter } = require("@azure/event-hubs");
const { SchemaRegistryClient } = require("@azure/schema-registry");
const { JsonSchemaSerializer } = require("@azure/schema-registry-json");

async function main(){
  const client = new SchemaRegistryClient(
    "<fully qualified namespace>",
    new DefaultAzureCredential()
  );
  const serializer = new JsonSchemaSerializer(client, {
    groupName: "<group>",
    messageAdapter: createEventDataAdapter(),
  });

  // Example Json schema
  const schema = JSON.stringify({  
    $schema: "http://json-schema.org/draft-04/schema#",
    $id: "person",
    title: "Student",
    description: "A student in the class",
    type: "object",
    properties: {
      name: {
        type: "string",
        description: "The name of the student",
      },
    },
    required: ["name"]
  });

  // Example value that matches the Json schema above
  const value = { name: "Bob" };

  // Serialize value to a message
  const message = await serializer.serialize(value, schema);

  // Deserialize a message to value
  const deserializedValue = await serializer.deserialize(message);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

The serializer doesn't check whether the deserialized value matches the schema but provides an option to implement such validation. The application can pass a validation callback function as one of the options to the deserialize method where schema validation can be implemented. To see how the validation might be implemented, please checkout the schemaRegistryJsonWithValidation sample.

Troubleshooting

The Json serializer communicates with the Schema Registry service as needed to register or query schemas and those service calls could throw a RestError. Furthermore, errors of type Error will be thrown when serialization or deserialization fails. The cause property will contain the underlying error that was thrown from the JSON parser.

Logging

Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the AZURE_LOG_LEVEL environment variable to info. Alternatively, logging can be enabled at runtime by calling setLogLevel in the @azure/logger:

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

Next steps

Please take a look at the samples directory for detailed examples on how to use this library.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.

Impressions