Présentation des fonctions définies par l'utilisateur (UDF)
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Une fonction définie par l'utilisateur (UDF) JavaScript est un type de transformation de message unique (SMT). Les UDF offrent un moyen flexible d'implémenter une logique de transformation personnalisée dans Pub/Sub, semblable aux UDF JavaScript BigQuery.
Les UDF acceptent un seul message en entrée, effectuent les actions définies sur l'entrée et renvoient le résultat du processus.
Les UDF présentent les propriétés clés suivantes :
Nom de la fonction : nom de la fonction JavaScript dans le code fourni que Pub/Sub applique aux messages.
Code : code JavaScript qui définit la logique de transformation.
Ce code doit contenir une fonction avec la signature suivante :
/*** Transforms a Pub/Sub message.* @return {(Object<string, (string | Object<string, string>)>|* null)} - To* filter a message, return `null`. To transform a message, return a map with* the following keys:* - (required) 'data' : {string}* - (optional) 'attributes' : {Object<string, string>}* Returning empty `attributes` will remove all attributes from the message.** @param {(Object<string, (string | Object<string, string>)>} - Pub/Sub* message. Keys:* - (required) 'data' : {string}* - (required) 'attributes' : {Object<string, string>}** @param {Object<string, any>} metadata - Pub/Sub message metadata.* Keys:* - (optional) 'message_id' : {string}* - (optional) 'publish_time': {string} YYYY-MM-DDTHH:MM:SSZ format* - (optional) 'ordering_key': {string}*/function<function_name>(message,metadata){// Perform custom transformation logicreturnmessage;// to filter a message instead, return `null`}
Entrées
Argument message : objet JavaScript représentant le message Pub/Sub. Il contient les propriétés suivantes :
data : (String, obligatoire) Charge utile du message.
attributes : (Object<String, String>, facultatif) Carte de paires clé/valeur représentant les attributs du message.
Argument metadata : objet JavaScript contenant des métadonnées immuables sur le message Pub/Sub :
message_id : (String, facultatif) ID unique du message.
publish_time : (String, facultatif) Heure de publication du message au format RFC 3339 (AAAA-MM-JJTHH:mm:ssZ).
ordering_key : (String, facultatif) Clé de tri du message, le cas échéant.
Sorties
Pour transformer un message, modifiez le contenu de message.data et message.attributes, puis renvoyez l'objet message modifié.
Pour filtrer un message, renvoyez null.
Comment les UDF transforment un message
Le résultat de l'exécution d'une UDF sur un message peut être l'un des suivants :
La fonction définie par l'utilisateur transforme un message.
La fonction définie par l'utilisateur renvoie null.
SMT de sujet : Pub/Sub renvoie une réponse positive à l'éditeur et inclut un ID de message dans la réponse pour les messages filtrés.
Pub/Sub ne stocke pas le message et ne l'envoie à aucun abonné.
SMT d'abonnement : Pub/Sub accuse réception de la distribution du message sans l'envoyer à un abonné.
La fonction définie par l'utilisateur génère une erreur.
SMT de sujet : Pub/Sub renvoie l'erreur à l'éditeur et ne publie aucun des messages.
SMT d'abonnement : Pub/Sub envoie un accusé de réception négatif pour le message.
Limites
Pub/Sub applique des limites de ressources aux UDF pour garantir l'efficacité des opérations de transformation. Voici quelques-unes de ces limites :
20 Ko de code maximum par fonction définie par l'utilisateur
Un temps d'exécution maximal de 500 ms par message
Voici quelques exemples de fonctions définies par l'utilisateur pour la publication et l'abonnement.
Fonction : convertir un entier correspondant à un jour de la semaine en chaîne correspondante
Lorsque vous ajoutez la UDF suivante à un sujet ou à un abonnement, les modifications suivantes sont apportées lors de la publication ou de la distribution des messages :
Pub/Sub applique la fonction au message. Si le message ne comporte pas de charge utile JSON, la UDF génère une erreur.
La fonction définie par l'utilisateur recherche un champ appelé dayOfWeek et, si la valeur de ce champ est un nombre compris entre 0 et 6, elle le convertit en jour de la semaine correspondant, tel que Monday. Si le champ n'existe pas ou si le nombre n'est pas compris entre 0 et 6, le code définit le champ dayOfWeek sur Unknown.
La fonction définie par l'utilisateur sérialise la charge utile modifiée dans le message.
Pub/Sub transmet le message mis à jour à l'étape suivante de votre pipeline.
Lorsque vous ajoutez la UDF suivante à un sujet ou à un abonnement, les modifications suivantes sont apportées lors de la publication ou de la distribution des messages :
Pub/Sub applique la fonction au message. Si le message ne comporte pas de charge utile JSON, la UDF génère une erreur.
La fonction UDF supprime le champ ssn de la charge utile du message (s'il existe).
La fonction définie par l'utilisateur sérialise la charge utile modifiée dans le message.
Pub/Sub transmet le message mis à jour à l'étape suivante de votre pipeline.
Fonction : filtrer et confirmer automatiquement des messages spécifiques
Lorsque vous ajoutez la UDF suivante à un sujet ou à un abonnement, les modifications suivantes sont apportées lors de la publication ou de la distribution des messages :
Pub/Sub applique la fonction au message. Si le message ne comporte pas de charge utile JSON, la UDF génère une erreur.
La fonction UDF vérifie si la charge utile contient un champ appelé region.
Si la valeur du champ region n'est pas US, la fonction renvoie la valeur "null", ce qui entraîne le filtrage du message par Pub/Sub.
Si la valeur du champ region est US, Pub/Sub transmet le message d'origine à l'étape suivante de votre pipeline.
Fonction : valider le contenu du message pour s'assurer que le montant n'est pas supérieur à 100
Lorsque vous ajoutez la UDF suivante à un sujet ou à un abonnement, les modifications suivantes sont apportées lors de la publication ou de la distribution des messages :
Pub/Sub applique la fonction au message. Si le message ne comporte pas de charge utile JSON, la UDF génère une erreur.
La fonction définie par l'utilisateur vérifie si le message contient un champ appelé amount.
Si la valeur du champ amount est supérieure à 100, la fonction génère une erreur.
Si la valeur du champ amount n'est pas supérieure à 100, la fonction renvoie le message d'origine.
Pub/Sub marque ensuite le message comme ayant échoué ou transmet le message d'origine à l'étape suivante de votre pipeline.
functionvalidateAmount(message,metadata){constdata=JSON.parse(message.data);if(data["amount"] > 100){thrownewError("Amount is invalid");}returnmessage;}
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[],[],null,["# User Defined Functions (UDFs) overview\n\nA JavaScript **User-Defined Function (UDF)** is a type of Single Message\nTransform (SMT). UDFs provide a flexible way to implement custom transformation\nlogic within Pub/Sub, similar to\n[BigQuery JavaScript UDFs](/bigquery/docs/user-defined-functions).\n\nUDFs accept a single message as input, perform the defined\nactions on the input, and return the result of the process.\n\nUDFs have the following key properties:\n\n- **Function name:** The name of the JavaScript function within the\n provided code that Pub/Sub applies to messages.\n\n- **Code:** The JavaScript code that defines the transformation logic.\n This code must contain a function with the following signature:\n\n /**\n * Transforms a Pub/Sub message.\n * @return {(Object\u003cstring, (string | Object\u003cstring, string\u003e)\u003e|* null)} - To\n * filter a message, return `null`. To transform a message, return a map with\n * the following keys:\n * - (required) 'data' : {string}\n * - (optional) 'attributes' : {Object\u003cstring, string\u003e}\n * Returning empty `attributes` will remove all attributes from the message.\n *\n * @param {(Object\u003cstring, (string | Object\u003cstring, string\u003e)\u003e} - Pub/Sub\n * message. Keys:\n * - (required) 'data' : {string}\n * - (required) 'attributes' : {Object\u003cstring, string\u003e}\n *\n * @param {Object\u003cstring, any\u003e} metadata - Pub/Sub message metadata.\n * Keys:\n * - (optional) 'message_id' : {string}\n * - (optional) 'publish_time': {string} YYYY-MM-DDTHH:MM:SSZ format\n * - (optional) 'ordering_key': {string}\n */\n function \u003cfunction_name\u003e(message, metadata) {\n // Perform custom transformation logic\n return message; // to filter a message instead, return `null`\n }\n\n### Inputs\n\n- **`message` argument:** A JavaScript object representing the\n Pub/Sub message. It contains the following properties:\n\n - `data`: (`String`, required) The message payload.\n\n - `attributes`: (`Object\u003cString, String\u003e`, optional) A map of key-value\n pairs representing message attributes.\n\n- **`metadata` argument:** A JavaScript object containing immutable metadata\n about the Pub/Sub message:\n\n - `message_id`: (`String`, optional) The unique ID of the message.\n\n - `publish_time`: (`String`, optional) The message's publish time in\n [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339) format (YYYY-MM-DDTHH:mm:ssZ).\n\n - `ordering_key`: (`String`, optional) The message's [ordering key](/pubsub/docs/ordering),\n if applicable.\n\n### Outputs\n\n- To transform a message, edit the contents of `message.data` and\n `message.attributes`, and return the altered `message` object.\n\n- To filter a message, return `null`.\n\nHow UDFs transform a message\n----------------------------\n\nThe result of running a UDF on a message can be one of the following:\n\n- The UDF transforms a message.\n\n- The UDF returns `null`.\n\n - Topic SMTs: Pub/Sub returns success to the publisher and\n includes a message ID in the response for the filtered messages.\n Pub/Sub does not store the message or send it to any subscribers.\n\n - Subscription SMTs: Pub/Sub acknowledges the message delivery\n without sending the message to a subscriber.\n\n- The UDF throws an error.\n\n - Topic SMTs: Pub/Sub returns the error to the publisher and\n does not publish any of the messages.\n\n - Subscription SMTs: Pub/Sub negatively acknowledges the message.\n\nLimitations\n-----------\n\nPub/Sub enforces resource limits on UDFs to ensure efficient\ntransformation operations. The limitations include:\n\n- A maximum of 20 KB of code per UDF\n- A maximum of 500 ms of execution time per message\n- Support for only [ECMAScript standard built-ins](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)\n- No calls to external APIs\n- No imports of external libraries\n\nSample UDFs\n-----------\n\nHere are some sample UDFs for publishing and subscribing.\n\n### Function: Convert a day of the week integer to the corresponding string\n\nWhen you add the following UDF to a topic or a subscription,\nthe following changes take place during message publish or delivery:\n\n1. Pub/Sub applies the function to the message. If the message does\n not have a JSON payload, the UDF throws an error.\n\n2. The UDF looks for a field called `dayOfWeek` and if the value of this field\n is a number between 0 and 6, converts it to a corresponding day of the week such\n as `Monday`. If the field does not exist or the number is not in the range of 0\n to 6, the code sets the `dayOfWeek` field to `Unknown`.\n\n3. The UDF serializes the modified payload back into the message.\n\n4. Pub/Sub passes the updated message to the next step in your\n pipeline.\n\n function intToString(message, metadata) {\n const data = JSON.parse(message.data);\n switch(`data[\"dayOfWeek\"]`) {\n case 0:\n data[\"dayOfWeek\"] = \"Sunday\";\n break;\n case 1:\n data[\"dayOfWeek\"] = \"Monday\";\n break;\n case 2:\n data[\"dayOfWeek\"] = \"Tuesday\";\n break;\n case 3:\n data[\"dayOfWeek\"] = \"Wednesday\";\n break;\n case 4:\n data[\"dayOfWeek\"] = \"Thursday\";\n break;\n case 5:\n data[\"dayOfWeek\"] = \"Friday\";\n break;\n case 6:\n data[\"dayOfWeek\"] = \"Saturday\";\n break;\n default:\n data[\"dayOfWeek\"] = \"Unknown\";\n }\n message.data = JSON.stringify(data);\n return message;\n }\n\n### Function: Redact a social security number\n\nWhen you add the following UDF to a topic or a subscription,\nthe following changes take place during message publish or delivery:\n\n1. Pub/Sub applies the function to the message. If the message\n does not have a JSON payload, the UDF throws an error.\n\n2. The UDF removes the field `ssn` from the message payload (if it exists).\n\n3. The UDF serializes the modified payload back into the message.\n\n4. Pub/Sub passes the updated message to the next step in your\n pipeline.\n\n function redactSSN(message, metadata) {\n const data = JSON.parse(message.data);\n delete data['ssn'];\n message.data = JSON.stringify(data);\n return message;\n }\n\n### Function: Filter out and auto-ack specific messages\n\nWhen you add the following UDF to a topic or a subscription,\nthe following changes take place during message publish or delivery:\n\n1. Pub/Sub applies the function to the message. If the message does\n not have a JSON payload, the UDF throws an error.\n\n2. The UDF checks if the payload contains a field called `region`.\n\n3. If the value of the `region` field is not `US`, the function returns\n null, causing Pub/Sub to filter the message.\n\n4. If the value of the `region` field is `US`, Pub/Sub passes the\n original message to the next step in your pipeline.\n\n function filterForUSRegion(message, metadata) {\n const data = JSON.parse(message.data);\n if (data[\"region\"] !== \"US\") {\n return null;\n }\n return message;\n }\n\n### Function: Validate message content to ensure the amount is not greater than 100\n\nWhen you add the following UDF to a topic or a subscription,\nthe following changes take place during message publish or delivery:\n\n1. Pub/Sub applies the function to the message. If the message does\n not have a JSON payload, the UDF throws an error.\n\n2. The UDF checks if the message contains a field called `amount`.\n\n3. If the value of the `amount` field is greater than `100`, the function\n throws an error.\n\n4. If the value of the `amount` field is not greater than `100`, the\n function returns the original message.\n\n5. Pub/Sub then either marks the message as failed, or\n passes the original message to the next step in your pipeline.\n\n function validateAmount(message, metadata) {\n const data = JSON.parse(message.data);\n if (data[\"amount\"] \u003e 100) {\n throw new Error(\"Amount is invalid\");\n }\n return message;\n }\n\nWhat's next\n-----------\n\n- [Choose between topic and subscription SMTs](/pubsub/docs/smts/choose-smts)\n\n- [Create a topic with SMTs](/pubsub/docs/smts/create-topic-smt)\n\n- [Create a subscription with SMTs](/pubsub/docs/smts/create-subscription-smt)"]]