انتقل إلى المحتوى

إنشاء أنواع GraphQL بلغة TypeScript لاستخدامها مع MongoDB — Numio

يُنشئ أنواع TypeScript لمستندات MongoDB من مخطط مُعلَّم بـ @entity و@id و@column و@link و@embedded و@map، باستخدام @graphql-codegen/typescript-mongodb. يحصل كل نوع @entity على نوع <Name>DbObject؛ وتُستبعد الحقول التي بلا توجيه.

إبقاء بنية مستندات MongoDB المخزّنة مُنمَّطة إلى جانب أنواع GraphQL API للكيان نفسه.

GraphQL Schema

TypeScript MongoDB

متى تستخدمها

  • إبقاء بنية مستندات MongoDB المخزّنة مُنمَّطة إلى جانب أنواع GraphQL API للكيان نفسه.
  • رؤية كيف تتحول مسارات @map ومراجع @link إلى كائنات متداخلة ومصفوفات ObjectId قبل كتابة شيفرة الوصول إلى البيانات.

طريقة الاستخدام

  1. الصق مخططًا تستخدم أنواعه @entity وتستخدم حقوله @id أو @column أو @link أو @embedded أو @map(path: ...).
  2. اقرأ أنواع DbObject قرب نهاية المخرجات؛ أما أنواع GraphQL نفسها فتُنشأ قبلها.
  3. انسخ النتيجة إلى ملف .ts؛ فهو يستورد ObjectId من الحزمة mongodb.

مخطط GraphQL مع توجيهات MongoDB

type User @entity {
  id: ID! @id
  email: String! @column @map(path: "login.email")
  profile: Profile! @embedded
  posts: [Post!]! @link
}

type Profile @entity(embedded: true) {
  name: String! @column
}

type Post @entity {
  id: ID! @id
  title: String! @column
}

أنواع DbObject في TypeScript

…
export type AdditionalEntityFields = {
  path?: InputMaybe<Scalars["String"]["input"]>
  type?: InputMaybe<Scalars["String"]["input"]>
}

import { ObjectId } from "mongodb"
export type UserDbObject = {
  _id: ObjectId
  login: {
    email: string
  }
  profile: ProfileDbObject
  posts: Array<PostDbObject["_id"]>
}

export type ProfileDbObject = {
  name: string
}

export type PostDbObject = {
  _id: ObjectId
  title: string
}

التفاصيل والقيود

يصبح @id هو _id: ObjectId، ويصبح @link هو _id للكيان المرتبط (Array<PostDbObject["_id"]> للقوائم)، وينشئ @map(path: "login.email") كائن login متداخلًا.

الحقول التي بلا توجيه (بلا @column أو @id أو @link أو @embedded) لا تُضمَّن في نوع DbObject؛ وتصبح الأعمدة القابلة لـ null خصائص Maybe<T> اختيارية.

تحتوي المخرجات أيضًا على الأنواع المعتادة لإضافة typescript (محذوفة أعلاه). يجري الإنشاء في Web Worker داخل متصفحك.

FAQ

هل أحتاج إلى تعريف التوجيهين @entity و@column في مخططي؟

لا. تضيف الإضافة تعريفات التوجيهات الخاصة بها، ولهذا يظهر أيضًا نوع input باسم AdditionalEntityFields في المخرجات.

كيف تُنمَّط المستندات المضمّنة؟

النوع المُعرَّف بـ @entity(embedded: true) يحصل على نوع DbObject بلا _id، والحقل الموسوم بـ @embedded يشير إليه، مثل profile: ProfileDbObject.

لماذا يغيب حقل عن نوع DbObject؟

الحقول المخزّنة هي فقط التي تحمل @id أو @column أو @link أو @embedded أو @map. أضف @column لتضمين حقل عادي.

المواصفات والمراجع