From 455162feae4d9f37d431c4e23ff8bd9957c12307 Mon Sep 17 00:00:00 2001 From: Evyatar Alush Date: Mon, 25 Nov 2024 12:21:09 +0200 Subject: [PATCH] docs: suite serialization --- .DS_Store | Bin 0 -> 6148 bytes website/docs/server_side_validations.md | 27 +----- website/docs/suite_serialization.md | 112 ++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 25 deletions(-) create mode 100644 .DS_Store create mode 100644 website/docs/suite_serialization.md diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0 { + // ... your validation tests ... +}); + +suite(formData); // Run the suite with some data + +const serializedSuite = SuiteSerializer.serialize(suite); +``` + +## SuiteSerializer.resume() + +This method takes a Vest suite instance and a serialized suite string. It applies the serialized state to the provided suite instance, effectively resuming the validation state from the serialized data. + +```js +import { SuiteSerializer } from 'vest'; + +const suite = create(data => { + // ... your validation tests ... +}); + +SuiteSerializer.resume(suite, serializedSuite); + +// The suite now has the state from the serializedSuite string +``` + +## Example: Client-Server Validation + +```js +// suite.js +import { create } from 'vest'; +import { SuiteSerializer } from 'vest'; + +const suite = create(data => { + test('username', 'Username is required', () => { + enforce(data.username).isNotBlank(); + }); + + test('email', 'Email is invalid', () => { + enforce(data.email).isEmail(); + }); +}); +``` + +```js +// server.js + +app.post('/submit', (req, res) => { + const formData = req.body; + + suite(formData); + + const serializedSuite = SuiteSerializer.serialize(suite); + + res.json({ serializedSuite }); +}); +``` + +```js +// client.js +import suite from './suite'; +import { SuiteSerializer } from 'vest'; + +const form = document.getElementById('myForm'); + +form.addEventListener('submit', (event) => { + event.preventDefault(); + + const formData = new FormData(form);   + + + fetch('/submit', { + method: 'POST', + body: formData, + }) + .then((response) => response.json()) + .then((data)   + => { + SuiteSerializer.resume(suite, data.serializedSuite); + }); +}); +``` + +In this example, the server performs the initial validation and sends the serialized suite state to the client. The client then resumes the suite with the received state, allowing for immediate feedback and a consistent validation experience across both environments.