محولات البيانات للتسلسل
استخدموا محولات بيانات tRPC لتسلسل أنواع البيانات المخصّصة مثل التواريخ أو BigInts وإلغاء تسلسلها.
محولات البيانات للتسلسل درس مجاني في tRPC End-to-End Type Safe APIs على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في tRPC End-to-End Type Safe APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة tRPC End-to-End Type Safe APIs 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
What are Data Transformers?
When building APIs, data often needs to be sent between different systems. This process is called serialization (converting data to a transportable format like JSON) and deserialization (converting it back).
tRPC's data transformers help handle complex data types that JSON doesn't natively support, ensuring they arrive on the client side just as they left the server.
JSON's Data Type Limits
JSON (JavaScript Object Notation) is great, but it has limitations. It natively supports strings, numbers, booleans, null, objects, and arrays.
- Dates: JSON represents dates as strings, losing their Date object functionality.
- BigInts: Large integer numbers (BigInt) are not a native JSON type.
- Maps, Sets, RegExps: These also don't have direct JSON representations.
Without transformers, these types can break or change unexpectedly when sent via tRPC.
Default tRPC Serialization
By default, tRPC uses standard JSON JSON.stringify() and JSON.parse() for data transfer. This means any data types not supported by JSON will be converted to their closest JSON representation.
For example, a JavaScript Date object will become an ISO 8601 string, and a BigInt will throw an error if not handled.
Introducing SuperJSON
To overcome JSON's limitations, tRPC allows you to plug in a custom data transformer. The most popular choice is superjson.
superjson is a library that extends JSON's capabilities, allowing it to serialize and deserialize many common JavaScript types, including Date, BigInt, Map, Set, and more, while preserving their original type.
Server Setup with SuperJSON
Integrating superjson on the server is straightforward. You pass it to initTRPC when initializing your tRPC instance. This tells tRPC to use superjson for all serialization.
First, install it: npm install superjson
import { initTRPC } from '@trpc/server';
import superjson from 'superjson';
// Initialize tRPC with superjson transformer
export const t = initTRPC.context().transformer(superjson).create();
// Example of a tRPC router definition (conceptual):
// export const appRouter = t.router({
// hello: t.procedure.query(() => {
// return { message: 'Hello, tRPC!', now: new Date() };
// }),
// });Client Setup with SuperJSON
On the client side, you also need to tell your tRPC client to use superjson. This ensures that the data received from the server is correctly deserialized back into its original JavaScript types.
The setup varies slightly depending on your client (e.g., React Query, vanilla client).
import { createTRPCReact } from '@trpc/react-query';
import superjson from 'superjson';
// import type { AppRouter } from '../server/trpc'; // Adjust path
// Initialize tRPC client with superjson transformer
export const trpc = createTRPCReact<any>({
transformer: superjson,
});
// Example client usage (conceptual):
// function MyComponent() {
// const hello = trpc.hello.useQuery();
// if (hello.data) {
// console.log(hello.data.now instanceof Date); // true!
// }
// return <p>...</p>;
// }Dates: Before & After
Let's see how superjson handles a Date object. Without it, a Date becomes a string. With superjson, it remains a Date object.
Run this example to see the serialization and deserialization process:
import superjson from 'superjson';
function main() {
const originalDate = new Date();
console.log("Original:", originalDate.toISOString());
console.log("Is Date (original):", originalDate instanceof Date);
// Simulate serialization (like tRPC server would do)
const serialized = superjson.stringify({ date: originalDate });
console.log("Serialized:", serialized);
// Simulate deserialization (like tRPC client would do)
const deserialized = superjson.parse(serialized) as { date: Date };
console.log("Deserialized:", deserialized.date.toISOString());
console.log("Is Date (deserialized):", deserialized.date instanceof Date);
}
main();BigInts: From String to Type
BigInt values are used for integers larger than Number.MAX_SAFE_INTEGER. JSON doesn't support them. superjson correctly serializes them as strings and deserializes them back into BigInt types.
Try this example:
import superjson from 'superjson';
function main() {
const originalBigInt = 9007199254740991n + 100n; // A BigInt
console.log("Original:", originalBigInt);
console.log("Type (original):", typeof originalBigInt);
// Simulate serialization
const serialized = superjson.stringify({ value: originalBigInt });
console.log("Serialized:", serialized);
// Simulate deserialization
const deserialized = superjson.parse(serialized) as { value: bigint };
console.log("Deserialized:", deserialized.value);
console.log("Type (deserialized):", typeof deserialized.value);
console.log("Is equal:", originalBigInt === deserialized.value);
}
main();Beyond Dates & BigInts
superjson isn't just for Date and BigInt. It also supports many other JavaScript types:
MapandSetRegExpErrorobjectsURLobjects- Even custom classes (with some configuration!)
This makes superjson a powerful tool for maintaining type fidelity across your tRPC application.
Transformer Check
Imagine you have a tRPC procedure that returns a JavaScript Date object and a BigInt. Which of the following statements are true about using superjson transformers in tRPC?
Recap: Data Transformers
In this lesson, we learned about tRPC's data transformers, specifically focusing on superjson.
- JSON's limitations prevent native serialization of types like
DateandBigInt. superjsonprovides a robust solution to serialize and deserialize these complex types, preserving their original form.- It requires configuration on both the tRPC server and client.
superjsonsupports many other types beyond Dates and BigInts, enhancing type safety across your application.
This ensures your data remains consistent and type-safe from end-to-end!
الأسئلة الشائعة
هل درس «محولات البيانات للتسلسل» مجاني؟
نعم — نص درس «محولات البيانات للتسلسل» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة tRPC End-to-End Type Safe APIs، انتقل إلى CoddyKit PRO. تتضمن دورة tRPC End-to-End Type Safe APIs 4 دروس في المجموع.
ماذا ستتعلم في «محولات البيانات للتسلسل»؟
استخدموا محولات بيانات tRPC لتسلسل أنواع البيانات المخصّصة مثل التواريخ أو BigInts وإلغاء تسلسلها. تتمرن على tRPC End-to-End Type Safe APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ tRPC End-to-End Type Safe APIs؟
لا تُشترط خبرة سابقة. tRPC End-to-End Type Safe APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.
كم من الوقت يستغرق درس «محولات البيانات للتسلسل»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس tRPC End-to-End Type Safe APIs هذا؟
نعم. كل درس في tRPC End-to-End Type Safe APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- معالجة أخطاء tRPC بسلاسة
- أنواع الأخطاء المخصّصة
- محولات البيانات للتسلسل
- تنسيق الأخطاء وملاحظات التحقق على مستوى الحقل