1. शुरू करने से पहले
इस कोडलैब में, आपको Firebase SQL Connect को Cloud SQL डेटाबेस के साथ इंटिग्रेट करने का तरीका बताया जाएगा. इससे आपको Friendly Exchange बनाने में मदद मिलेगी. यह रीयलटाइम इमोजी स्टॉक मार्केट वेब ऐप्लिकेशन है.
पूरे किए गए ऐप्लिकेशन में, SQL Connect की बेहतर सुविधाएं दिखाई गई हैं. इनमें ये शामिल हैं:
- नेटिव एसक्यूएल:
_executeऔर_selectका इस्तेमाल करके, डेटा में बदलाव करने वाली कंप्यूटर प्रोग्राम की भाषा (डीएमएल) के जटिल स्टेटमेंट और कॉमन टेबल एक्सप्रेशन (सीटीई) को सुरक्षित तरीके से लागू करें. - एसक्यूएल व्यू:
@viewडायरेक्टिव का इस्तेमाल करके, डाइनैमिक Postgres क्वेरी पर आधारित स्ट्रिक्ट और टाइप-सेफ़ GraphQL ऑब्जेक्ट बनाएं. - रीयलटाइम सदस्यताएं:
@refreshट्रिगर का इस्तेमाल करके, अपने फ़्रंटएंड यूज़र इंटरफ़ेस (यूआई) को सिंक में रखें. - ऐटॉमिक लेन-देन:
@transactionऔर@checkका इस्तेमाल करके, एक साथ कई कार्रवाइयां करें और स्थिति की पुष्टि करें. - (ज़रूरी नहीं) जियोस्पेशल और वेक्टर सर्च: PostGIS और pgvector का इस्तेमाल करके, किसी उपयोगकर्ता के निर्देशांकों के आस-पास मौजूद लोकप्रिय ऐसेट ढूंढें और सिमैंटिक सर्च करें.
- (ज़रूरी नहीं) कस्टम रिज़ॉल्वर: एआई की मदद से कारोबार के बारे में हेडलाइन जनरेट करने के लिए, कस्टम Cloud Run लॉजिक को अपने GraphQL स्कीमा से कनेक्ट करें.
ज़रूरी शर्तें
आपको JavaScript/TypeScript, React, और बुनियादी SQL सिंटैक्स की अच्छी जानकारी होनी चाहिए.
आपको क्या सीखने को मिलेगा
- डिक्लेरेटिव GraphQL और रॉ PostgreSQL लॉजिक के बीच के अंतर को कम करने के लिए, नेटिव एसक्यूएल का इस्तेमाल कैसे करें.
- PostGIS जैसे Postgres एक्सटेंशन को सीधे अपनी डेटाबेस क्वेरी में इंटिग्रेट करने का तरीका.
- एटॉमिक
@transactionब्लॉक का इस्तेमाल करके, मुश्किल लॉजिक को लागू करने का तरीका. - लीडरबोर्ड और आंकड़ों के लिए, टाइप-सेफ़
@viewsबनाने का तरीका. @refreshका इस्तेमाल करके, रीयलटाइम सदस्यताएं सेट अप करने का तरीका.
आपको इन चीज़ों की ज़रूरत होगी
- Git
- Visual Studio Code
- Node.js इंस्टॉल करें
- पे-ऐज़-यू-गो ब्लेज़ प्लान वाला Firebase प्रोजेक्ट. यह कस्टम रिज़ॉल्वर और Vertex AI के लिए ज़रूरी है.
2. डेवलपमेंट एनवायरमेंट सेट अप करना
इस चरण में, आपको फ़्रंटएंड सेट अप करने और ऐडवांस सुविधाओं के लिए Cloud SQL इंस्टेंस को कॉन्फ़िगर करने का तरीका बताया गया है.
- प्रोजेक्ट रिपॉज़िटरी का क्लोन बनाएं और ऐप्लिकेशन के लिए ज़रूरी डिपेंडेंसी इंस्टॉल करें:
git clone https://github.com/firebaseextended/codelab-dataconnect-web cd codelab-dataconnect-web git switch emoji-init npm install
- Visual Studio Code का इस्तेमाल करके, क्लोन किया गया फ़ोल्डर खोलें. इसके बाद, Firebase SQL Connect Visual Studio Extension इंस्टॉल करें.
- अपने टर्मिनल में, पक्का करें कि Firebase CLI पूरी तरह से अप-टू-डेट हो. यह
@refreshऔर नेटिव एसक्यूएल जैसी नई सुविधाओं के लिए ज़रूरी है:
npm uninstall -g firebase-tools npm install -g firebase-tools firebase login firebase use your-project-id firebase init
(होस्टिंग, पुष्टि करने का तरीका, और एसक्यूएल कनेक्ट चुनें).
SQL Connect SDK जनरेट करें: यह कमांड चलाएं:
firebase dataconnect:sdk:generate
- अपने वेब ऐप्लिकेशन को Firebase प्रोजेक्ट से कनेक्ट करें: Firebase कंसोल का इस्तेमाल करके, अपने वेब ऐप्लिकेशन को Firebase प्रोजेक्ट में रजिस्टर करें:
- अपना प्रोजेक्ट खोलें. इसके बाद, ऐप्लिकेशन जोड़ें पर क्लिक करें (वेब आइकॉन चुनें).
- फ़िलहाल, एसडीके टूल के सेटअप और कॉन्फ़िगरेशन सेटअप को अनदेखा करें. हालांकि, यह पक्का करें कि आपने जनरेट किए गए
firebaseConfigऑब्जेक्ट को कॉपी कर लिया हो. - अपने कोड एडिटर में
lib/firebase.tsxखोलें और मौजूदा प्लेसहोल्डर को उस कॉन्फ़िगरेशन से बदलें जिसे आपने अभी कॉपी किया है:
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "PROJECT_ID.firebaseapp.com",
projectId: "PROJECT_ID",
storageBucket: "PROJECT_ID.firebasestorage.app",
messagingSenderId: "SENDER_ID",
appId: "APP_ID"
};
- डेवलपमेंट सर्वर चलाएं:
npm run dev
3. स्टार्टर कोडबेस की समीक्षा करना
इस सेक्शन में, आपको ऐप्लिकेशन के स्टार्टर कोडबेस के मुख्य हिस्सों के बारे में जानकारी मिलेगी. आपको नए सिरे से स्कीमा और क्वेरी लिखनी होंगी. हालांकि, यह समझना ज़रूरी है कि फ़्रंटएंड को SQL Connect के साथ इंटरैक्ट करने के लिए कैसे सेट अप किया जाता है.
फ़ोल्डर और फ़ाइल का स्ट्रक्चर
dataconnect/ डायरेक्ट्री
इस फ़ोल्डर में, आपके बैकएंड की परिभाषा होती है. इसमें आपके डेटाबेस स्ट्रक्चर से लेकर, वे खास एसक्यूएल क्वेरी शामिल होती हैं जिन्हें आपका ऐप्लिकेशन चला सकता है.
schema/schema.gql: यहां स्टैंडर्ड GraphQL टाइप का इस्तेमाल करके, अपनी बेस Postgres टेबल तय की जाएंगी.schema/views.gql: यहां@viewडायरेक्टिव का इस्तेमाल करके, सिर्फ़ पढ़ने के लिए उपलब्ध जटिल एसक्यूएल व्यू (जैसे, लीडरबोर्ड) तय किए जाएंगे.friendly-exchange/queries.gqlऔरmutations.gql: ये आपके "कनेक्टर" हैं. यहां आपको उन क्वेरी और नेटिव एसक्यूएल (_execute,_select) के बारे में बताना होगा जिन्हें आपका ऐप्लिकेशन इस्तेमाल कर सकता है.dataconnect.yaml: यह कॉन्फ़िगरेशन फ़ाइल है. इससे एसडीके जनरेट करने और Cloud SQL डिप्लॉयमेंट की सेटिंग तय होती हैं.
lib/ डायरेक्ट्री
इसमें ऐप्लिकेशन लॉजिक, पुष्टि करने की सुविधा, और Firebase SQL Connect SDK के साथ इंटरैक्शन शामिल होता है.
firebase.tsx: यह आपके Firebase ऐप्लिकेशन, Auth, और SQL Connect इंस्टेंस को शुरू करने की प्रोसेस को मैनेज करता है.ExchangeService.tsx: यह आपके React कॉम्पोनेंट और डेटाबेस के बीच का ब्रिज है. यह जनरेट किए गए एसडीके फ़ंक्शन (जैसे किbuyStockयाsellStock) को स्टैंडर्ड एसिंक फ़ंक्शन में रैप करता है, ताकि गड़बड़ी का पता लगाया जा सके, कारोबारी लॉजिक को मैनेज किया जा सके, और सूचनाएं दिखाई जा सकें.
जनरेट किया गया एसडीके
SQL Connect में कोई क्वेरी या म्यूटेशन लिखने पर, VS Code एक्सटेंशन अपने-आप एक टाइप-सेफ़ SDK जनरेट करता है. इस प्रोजेक्ट में, फ़्रंटएंड इन फ़ंक्शन को सीधे तौर पर @dataconnect/generated से इंपोर्ट करता है.
4. इमोजी एक्सचेंज के लिए स्कीमा तय करना
इस सेक्शन में, आपको ट्रेडिंग ऐप्लिकेशन में मौजूद मुख्य इकाइयों के स्ट्रक्चर और उनके बीच के संबंधों के बारे में बताना होगा. User, Emoji, StockOwnership, Event, और PriceHistory जैसी इकाइयों को डेटाबेस टेबल पर मैप किया जाता है. साथ ही, Firebase SQL Connect और GraphQL स्कीमा डायरेक्टिव का इस्तेमाल करके संबंध बनाए जाते हैं.
इस स्कीमा को लागू करने के बाद, आपका ऐप्लिकेशन खरीदारी/बिक्री के लेन-देन को पूरा करने, ग्लोबल लीडरबोर्ड को अपडेट करने, और स्थानीय भू-स्थानिक रुझानों को मैप करने जैसे सभी काम करने के लिए तैयार हो जाएगा.
मुख्य इकाइयां और संबंध
- इमोजी: इसमें मुख्य जानकारी होती है. जैसे, सिंबल, नाम, कीमत, और ट्रेंड. ऐप्लिकेशन, इस जानकारी का इस्तेमाल करके मार्केट को दिखाता है.
- उपयोगकर्ता: यह ट्रेडर की प्रोफ़ाइल, उपलब्ध पॉइंट (मुद्रा), और स्थानीय रडार स्कैनिंग के लिए भौगोलिक निर्देशांक को ट्रैक करता है.
- संबंध:
StockOwnershipजॉइन टेबल से यह पता चलता है कि किसी उपयोगकर्ता के पास किसी इमोजी के कितने शेयर हैं.EventऔरPriceHistoryटाइप, ऐसे लेज़र के तौर पर काम करते हैं जिन्हें बदला नहीं जा सकता. ये समय के साथ, बाज़ार पर पड़ने वाले असर और पिछली कीमतों को लॉग करते हैं.
उपयोगकर्ता टेबल सेट अप करना
User टाइप, सिस्टम में किसी ट्रेडर को तय करता है. साथ ही, उसके बैलेंस, भूमिका, और भौगोलिक डेटा से जुड़ी क्वेरी के लिए उसकी मौजूदगी की जगह को ट्रैक करता है.
इस कोड स्निपेट को कॉपी करके अपनी dataconnect/schema/schema.gql फ़ाइल में चिपकाएं:
# Users
# user-stockOwnership is a one-to-many relationship, user-events is a one-to-many relationship
# Utilizes the Firebase Auth uid expression as the primary key
type User @table {
id: String! @default(expr: "auth.uid")
username: String!
profileImage: String
role: String! @default(value: "USER")
points: Float! @default(value: 100.0)
city: String @default(value: "Las Vegas")
latitude: Float @default(value: 36.1699)
longitude: Float @default(value: -115.1398)
}
अहम जानकारी:
id: यह@default(expr: "auth.uid")का इस्तेमाल करके, सीधे तौर पर Firebase Authentication से जुड़ता है. इससे यह पक्का होता है कि डेटाबेस की पहचान और पुष्टि करने वाले की पहचान, सुरक्षित तरीके से 1:1 है. इससे उपयोगकर्ताओं को आईडी स्पूफ़ करने से रोका जा सकता है.points: कारोबार के लिए इस्तेमाल की जाने वाली वर्चुअल मुद्रा. नए उपयोगकर्ताओं के लिए, यह डिफ़ॉल्ट रूप से100.0पर सेट होती है.
इमोजी टेबल सेट अप करना
Emoji टाइप से, कारोबार के लिए उपलब्ध मुख्य ऐसेट के बारे में जानकारी मिलती है. इसमें स्टैंडर्ड टेक्स्ट सर्च के लिए फ़ील्ड भी शामिल होते हैं.
इस कोड स्निपेट को कॉपी करके अपनी dataconnect/schema/schema.gql फ़ाइल में चिपकाएं:
# Emojis
# emoji-stockOwnership is a one-to-many relationship, emoji-priceHistory is a one-to-many relationship
# Implements @searchable directives for full-text search
type Emoji @table {
id: UUID! @default(expr: "uuidV4()")
symbol: String!
name: String! @searchable
tags: [String!]
description: String! @searchable
currentPrice: Float! @default(value: 10.0)
trend: Float! @default(value: 0.0)
}
अहम जानकारी:
name&description:@searchableडायरेक्टिव का इस्तेमाल करके, इन कॉलम को स्टैंडर्ड फ़ुल-टेक्स्ट सर्च के लिए ऑप्टिमाइज़ करता है.
StockOwnership टेबल सेट अप करना
StockOwnership टाइप एक जॉइन टेबल है. यह उन उपयोगकर्ताओं और उनके पास मौजूद इमोजी के बीच मेनी-टू-मेनी रिलेशनशिप को मैनेज करती है. इस स्निपेट को कॉपी करके अपनी dataconnect/schema/schema.gql फ़ाइल में चिपकाएं:
# Join table for many-to-many relationship between users and emojis
# The 'key' param signifies the primary key(s) of this table
# In this case, the keys are [user, emoji], the generated fields of the reference types
type StockOwnership @table(key: ["user", "emoji"]) {
user: User!
emoji: Emoji!
shares: Int! @default(value: 0)
}
अहम जानकारी:
key: ["user", "emoji"]: कंपोज़िट प्राइमरी की बनाता है. किसी उपयोगकर्ता के पास एक ही इमोजी के लिए दो अलग-अलग रिकॉर्ड नहीं हो सकते. यह हर जोड़े के लिए यूनीकनेस लागू करता है.- इंप्लिसिट रेफ़रंस:
UserऔरEmojiटाइप को सीधे तौर पर रेफ़रंस करके, SQL Connect बैकग्राउंड में अपने-आप फ़ॉरेन कीuserId: String!औरemojiId: UUID!जनरेट करता है.
Event और PriceHistory टेबल सेट अप करना
ये टाइप, ऐप्लिकेशन के लेज़र को दिखाते हैं. इनमें यह जानकारी लॉग की जाती है कि क्या हुआ और कीमतों में कैसे बदलाव हुआ. फ़ाइनल स्निपेट को कॉपी करके अपनी dataconnect/schema/schema.gql फ़ाइल में चिपकाएं:
# Events
# Event-User is a many-to-one relationship, Event-Emoji is a many-to-one relationship
# Evaluates the createdAt timestamp purely on the server side using the request.time expression
type Event @table {
id: UUID! @default(expr: "uuidV4()")
user: User!
emoji: Emoji!
impact: Float!
description: String!
createdAt: Timestamp! @default(expr: "request.time")
}
# Price History
# PriceHistory-Emoji is a many-to-one relationship
type PriceHistory @table {
id: UUID! @default(expr: "uuidV4()")
emoji: Emoji!
price: Float!
recordedAt: Timestamp! @default(expr: "request.time")
}
अहम जानकारी:
createdAt&recordedAt:@default(expr: "request.time")का इस्तेमाल करके, डेटाबेस ट्रांज़ैक्शन के ठीक समय पर अपने-आप सेट हो जाता है. इससे क्लाइंट, टाइमस्टैंप में बदलाव नहीं कर पाते.
अपने-आप जनरेट होने वाले फ़ील्ड और डिफ़ॉल्ट वैल्यू
स्कीमा, @default(expr: "uuidV4()") और @default(expr: "auth.uid") जैसे एक्सप्रेशन पर निर्भर करता है. इससे यूनीक आईडी अपने-आप जनरेट होते हैं और मालिकाना हक लागू होता है. इसके लिए, क्लाइंट ऐप्लिकेशन को आईडी देने की ज़रूरत नहीं होती.
5. बाज़ार और उपयोगकर्ता का डेटा वापस पाना
इस सेक्शन में, आपको अपने डेटाबेस में मॉक मार्केट डेटा डालना होगा. इसके बाद, कनेक्टर (क्वेरी) और TypeScript कोड लागू करना होगा, ताकि वेब ऐप्लिकेशन में इन कनेक्टर को कॉल किया जा सके. आखिर तक, आपका ऐप्लिकेशन डेटाबेस से सीधे तौर पर लाइव इमोजी मार्केट, उपयोगकर्ता प्रोफ़ाइलें, और लीडरबोर्ड को डाइनैमिक तरीके से फ़ेच और दिखा सकेगा.
मॉक मार्केट और उपयोगकर्ता का डेटा डालना
- VSCode में,
dataconnect/seed.gqlखोलें. - पक्का करें कि Firebase SQL Connect एक्सटेंशन में एम्युलेटर चल रहे हों या आपका Cloud SQL इंस्टेंस कनेक्ट हो.
- आपको फ़ाइल के सबसे ऊपर, Run (local) या Run (Production) CodeLens बटन दिखेगा. अपने डेटाबेस में मॉक इमोजी डेटा और कीमत के इतिहास की शुरुआती जानकारी डालने के लिए, इस पर क्लिक करें.
- यह पुष्टि करने के लिए कि डेटा को सही तरीके से जोड़ा गया है, SQL Connect Execution टर्मिनल देखें.
बुनियादी क्वेरी लागू करना
सबसे पहले, अपने स्कीमा में तय की गई स्टैंडर्ड टेबल को क्वेरी करते हैं.
-
dataconnect/friendly-exchange/queries.gqlखोलें. - डैशबोर्ड का डेटा, उपयोगकर्ता की प्रोफ़ाइलें, और कीमत में हुए बदलाव का बुनियादी इतिहास वापस पाने के लिए, यहां दी गई क्वेरी जोड़ें:
# Get dashboard data including top emojis by price and recent market events
query GetDashboardData
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
emojis(orderBy: [{ currentPrice: DESC }]) {
id
symbol
name
description
currentPrice
trend
}
events(orderBy: [{ createdAt: DESC }], limit: 15) {
id
description
impact
createdAt
user {
username
profileImage
}
emoji {
symbol
}
}
}
# Get current authenticated user profile and their stock ownership using auth.uid
query GetUserProfile @auth(level: USER) {
user(id_expr: "auth.uid") {
points
username
profileImage
role
stockOwnerships_on_user {
shares
emoji {
id
symbol
currentPrice
name
}
}
city
latitude
longitude
}
}
# Get price history for a specific emoji ordered by time
query GetPriceHistory($emojiId: UUID!, $limit: Int)
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
priceHistories(
where: { emojiId: { eq: $emojiId } }
orderBy: [{ recordedAt: ASC }]
limit: $limit
) {
price
recordedAt
}
}
अहम जानकारी:
emojis()/events(): ये GraphQL क्वेरी फ़ील्ड, आपकी टेबल से सीधे डेटा फ़ेच करने के लिए अपने-आप जनरेट होते हैं.id_expr: "auth.uid": यह फ़ंक्शन, पुष्टि किए गए मौजूदा Firebase उपयोगकर्ता के टोकन से मेल खाने वाली उपयोगकर्ता प्रोफ़ाइल को फ़ेच करके, ऐक्सेस को सुरक्षित करता है._on_: इससे, फ़ॉरेन की रिलेशनशिप वाले किसी जुड़े हुए टाइप के फ़ील्ड को सीधे तौर पर ऐक्सेस किया जा सकता है.stockOwnerships_on_userएक क्वेरी में उपयोगकर्ता के पूरे पोर्टफ़ोलियो को फ़ेच करता है.insecureReason:PUBLICको कार्रवाइयां दिखाने के लिए, यह एट्रिब्यूट ज़रूरी है. इसमें साफ़ तौर पर बताया गया है कि पुष्टि किए बिना इस डेटा को सार्वजनिक करना सुरक्षित क्यों है.
टाइप-सेफ़ एसक्यूएल व्यू बनाना
कस्टम एसक्यूएल लिखने से पहले, यह समझना ज़रूरी है कि Firebase SQL Connect, क्वेरी को अलग-अलग तरीकों से कैसे हैंडल करता है:
- स्टैंडर्ड GraphQL: यह बुनियादी CRUD और सामान्य संबंधों के लिए सबसे अच्छा है. इसमें टाइप की सुरक्षा का पूरा ध्यान रखा जाता है.
- एसक्यूएल व्यू (
@view): यह सिर्फ़ पढ़ने के लिए उपलब्ध है. यह जटिल एसक्यूएल (जैसे, विंडो फ़ंक्शन का इस्तेमाल करके लीडरबोर्ड) के लिए सबसे सही है. इसमें आपको क्लाइंट को एक स्ट्रिक्ट, टाइप-सेफ़ GraphQL ऑब्जेक्ट वापस भेजना होता है. - नेटिव एसक्यूएल (
_execute/_select): यह सीधे तौर पर डीएमएल, सीटीई या PostGIS एक्सटेंशन को लागू करने के लिए सबसे सही है. इसमें, कंपाइल-टाइम टाइपिंग के बजाय, एक्ज़ीक्यूशन-टाइम फ़्लेक्सिबिलिटी को प्राथमिकता दी जाती है. इससे डाइनैमिक JSON मिलता है.
लीडरबोर्ड और स्पार्कलाइन चार्ट बनाने के लिए, हमें मूविंग एवरेज का हिसाब लगाना होता है और उपयोगकर्ताओं को रैंक करना होता है. यह @view के इस्तेमाल का उदाहरण है.
-
dataconnect/schema/views.gqlखोलें. - सर्वर पर ज़रूरी आंकड़े कैलकुलेट करने के लिए, ये व्यू जोड़ें:
# Rank users on a leaderboard based on their total net worth
type TopTrader
@view(
sql: """
SELECT
u.id,
u.username,
u.profile_image,
(u.points + COALESCE(SUM(so.shares * e.current_price), 0)) AS net_worth,
RANK() OVER (ORDER BY (u.points + COALESCE(SUM(so.shares * e.current_price), 0)) DESC) AS rank
FROM "user" u
LEFT JOIN stock_ownership so ON u.id = so.user_id
LEFT JOIN emoji e ON so.emoji_id = e.id
WHERE u.id != 'system_market_maker'
GROUP BY u.id, u.username, u.profile_image, u.points
"""
) {
id: String
username: String
profileImage: String
netWorth: Float
rank: Int
}
# Identify the top shareholder (whale) for each emoji and their total ownership percentage
type EmojiWhaleStat
@view(
sql: """
WITH total_shares AS (
SELECT emoji_id, SUM(shares) AS total_supply
FROM stock_ownership WHERE shares > 0 GROUP BY emoji_id
),
ranked_holders AS (
SELECT
so.emoji_id, u.username AS whale_username, u.profile_image AS whale_profile_image,
so.shares AS whale_shares, ts.total_supply,
ROUND((so.shares::DECIMAL / NULLIF(ts.total_supply, 0)) * 100, 2) AS whale_percentage,
RANK() OVER (PARTITION BY so.emoji_id ORDER BY so.shares DESC) AS holder_rank
FROM stock_ownership so
JOIN "user" u ON u.id = so.user_id
JOIN total_shares ts ON ts.emoji_id = so.emoji_id
WHERE so.shares > 0
)
SELECT emoji_id, whale_username, whale_profile_image, whale_shares, total_supply, whale_percentage
FROM ranked_holders WHERE holder_rank = 1
"""
) {
emojiId: UUID
whaleUsername: String
whaleProfileImage: String
whaleShares: Int
totalSupply: Int
whalePercentage: Float
}
# Calculate the moving average of historical prices for each emoji
type EmojiHistoryStat
@view(
sql: """
SELECT
emoji_id, price, recorded_at,
AVG(price) OVER (PARTITION BY emoji_id ORDER BY recorded_at ROWS BETWEEN 4 PRECEDING AND CURRENT ROW) as moving_average
FROM price_history
"""
) {
emojiId: UUID
price: Float
recordedAt: Timestamp
movingAverage: Float
}
# Combine recent price updates and major news events into a single chronological feed
type TickerFeed
@view(
sql: """
WITH latest_prices AS (
SELECT emoji_id, MAX(recorded_at) as last_trade_time
FROM price_history GROUP BY emoji_id
)
SELECT
'PRICE' as type, e.symbol, e.name, e.current_price, e.trend,
'' as description, lp.last_trade_time as event_time
FROM emoji e JOIN latest_prices lp ON e.id = lp.emoji_id
UNION ALL
SELECT
'NEWS' as type, e.symbol, '' as name, 0 as current_price, 0 as trend,
ev.description, ev.created_at as event_time
FROM event ev JOIN emoji e ON ev.emoji_id = e.id
"""
) {
type: String
symbol: String
name: String
currentPrice: Float
trend: Float
description: String
eventTime: Timestamp
}
# Retrieve the 15 most recent price points for each emoji to render sparkline charts
type EmojiSparkline
@view(
sql: """
WITH RankedPrices AS (
SELECT
emoji_id, price, recorded_at,
ROW_NUMBER() OVER(PARTITION BY emoji_id ORDER BY recorded_at DESC) as rn
FROM price_history
)
SELECT emoji_id, price, recorded_at
FROM RankedPrices WHERE rn <= 15 ORDER BY recorded_at ASC
"""
) {
emojiId: UUID
price: Float
recordedAt: Timestamp
}
अब dataconnect/friendly-exchange/queries.gql खोलें और अपने नए व्यू से डेटा फ़ेच करने के लिए, TODOs को बदलें:
# Get emoji whale statistics to identify top shareholders from emojiWhaleStats view
query GetEmojiWhaleStats
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
emojiWhaleStats {
emojiId
whaleUsername
whaleProfileImage
whaleShares
totalSupply
whalePercentage
}
}
# Get historical price and moving average stats for a specific emoji from emojiHistoryStats view
query GetEmojiHistoryStats($emojiId: UUID!)
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
emojiHistoryStats(
where: { emojiId: { eq: $emojiId } }
orderBy: [{ recordedAt: ASC }]
limit: 50
) {
price
movingAverage
recordedAt
}
}
# List top traders ordered by rank from topTraders view
query GetTopTraders
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
topTraders(orderBy: [{ rank: ASC }]) {
id
username
profileImage
netWorth
rank
}
}
# Get chronological market ticker feed of recent events from tickerFeeds view
query GetChronologicalTicker
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
tickerFeeds(orderBy: [{ eventTime: DESC }], limit: 30) {
type
symbol
name
currentPrice
trend
description
eventTime
}
}
# Get simple price points for rendering emoji sparkline charts from emojiSparklines view
query GetEmojiSparklines
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
emojiSparklines {
emojiId
price
recordedAt
}
}
अहम जानकारी
@view: यह सर्वर पर जटिल डेटाबेस लॉजिक को शामिल करता है. साथ ही, आपके क्लाइंट-साइड कोड को टाइप किया गया रखता है. SQL Connect, आपके@viewटाइप के GraphQL फ़ील्ड को, आपकेSELECTस्टेटमेंट से मिले कॉलम से मैप करता है.- सिर्फ़ पढ़ने का ऐक्सेस: व्यू में प्राइमरी कुंजियां नहीं होती हैं और इनमें सीधे तौर पर बदलाव नहीं किया जा सकता.
- क्वेरी जनरेट करना: ध्यान दें कि
topTraders()औरemojiSparklines(), स्टैंडर्ड टेबल को क्वेरी करने के तरीके से ही काम करते हैं.
खोज क्वेरी लागू करना
SQL Connect, आपके स्कीमा में @searchable डायरेक्टिव के तौर पर मार्क किए गए किसी भी फ़ील्ड के लिए, स्टैंडर्ड सर्च क्वेरी अपने-आप जनरेट करता है.
फ़ुल-टेक्स्ट सर्च की सुविधा चालू करने के लिए, dataconnect/friendly-exchange/queries.gql में यह क्वेरी जोड़ें:
# Search emojis using full-text search query
query SearchEmojis($query: String)
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
emojis_search(query: $query) {
id
symbol
name
description
currentPrice
trend
}
}
अहम जानकारी
emojis_search: यह अपने-आप जनरेट होने वाला क्वेरी फ़ील्ड है. इसे इसलिए बनाया गया है, क्योंकि आपनेEmojiस्कीमा में मौजूदnameऔरdescriptionफ़ील्ड पर@searchableलागू किया था.
एसडीके टूल जनरेट करना
आपने अपनी GraphQL फ़ाइलों में नई क्वेरी और व्यू तय किए हैं. इसलिए, आपको एसडीके जनरेटर चलाना होगा, ताकि आपका TypeScript फ़्रंटएंड उनका सुरक्षित तरीके से इस्तेमाल कर सके.
अपना टर्मिनल खोलें और यह कमांड चलाएं:
firebase dataconnect:sdk:generate
वेब ऐप्लिकेशन में क्वेरी इंटिग्रेट करना
Firebase SQL Connect कंपाइलर, आपके .gql फ़ाइलों के आधार पर SDK टूल जनरेट करता है. इसे रीयलटाइम ऐप्लिकेशन के तौर पर डिज़ाइन किया गया है. इसलिए, आपको कई कॉम्पोनेंट में जनरेट किए गए क्वेरी रेफ़रंस के साथ-साथ subscribe तरीके का इस्तेमाल करना होगा.
नीचे दी गई फ़ाइलों में मौजूद खाली useEffect ब्लॉक को यहां दिए गए लॉजिक से बदलें:
1. होम पेज (
app/page.tsx
)
import { subscribe } from "@firebase/data-connect";
import {
getDashboardDataRef,
searchEmojisRef,
getChronologicalTickerRef,
getUserProfileRef,
} from "@dataconnect/generated";
// Inside the Home component:
useEffect(() => {
// Subscribe to realtime updates for the main market dashboard data including top emojis and recent events
const unsubscribe = subscribe(
getDashboardDataRef(),
(res) => {
if (res.data) setDashboardData(res.data);
setIsDashboardLoading(false);
},
(err) => {
console.error("Dashboard Realtime Error:", err);
setIsDashboardLoading(false);
},
);
return () => unsubscribe();
}, [user]);
useEffect(() => {
// Subscribe to a realtime chronological ticker feed combining recent price updates and major news events
const unsubscribe = subscribe(
getChronologicalTickerRef(),
(res) => {
if (res.data) setTickerData(res.data);
},
(err) => console.error("Ticker Realtime Error:", err),
);
return () => unsubscribe();
}, []);
useEffect(() => {
if (loading || !user) return;
// Subscribe to realtime updates for the authenticated user's profile and stock ownership
const unsubscribe = subscribe(
getUserProfileRef(),
(res) => {
if (res.data) setProfileData(res.data);
},
(err) => console.error("Profile Error:", err),
);
return () => unsubscribe();
}, [user, loading]);
useEffect(() => {
if (!debouncedSearch) {
setSearchData(null);
return;
}
// Subscribe to realtime full-text search results for emojis based on user input
const unsubscribe = subscribe(
searchEmojisRef({ query: debouncedSearch }),
(res) => {
if (res.data) setSearchData(res.data.emojis_search);
setIsSearchLoading(false);
},
(err) => {
console.error("Text Search Error:", err);
setIsSearchLoading(false);
},
);
return () => unsubscribe();
}, [debouncedSearch]);
2. उपयोगकर्ता की प्रोफ़ाइल के कॉम्पोनेंट
app/profile/page.tsx
, update the hooks:
import { subscribe } from "@firebase/data-connect";
import { getUserProfileRef } from "@dataconnect/generated";
useEffect(() => {
// Subscribe to realtime updates for the authenticated user's profile and stock ownership
const unsubscribe = subscribe(
getUserProfileRef(),
(res) => {
if (res.data) {
setData(res.data);
}
setIsLoading(false);
},
(err) => {
console.error("Profile Realtime Error:", err);
setIsLoading(false);
},
);
return () => unsubscribe();
}, []);
components/NavBar.tsx
:
useEffect(() => {
// Subscribe to realtime updates for the authenticated user's profile and stock ownership
const unsub = subscribe(
getUserProfileRef(),
(res) => {
if (res.data) setData(res.data);
},
(err) => console.error("Navbar Balance Realtime Error:", err),
);
return () => unsub();
}, []);
components/FloatingMenu.tsx के लिए, मैन्युअल const { data } ऑब्जेक्ट को जनरेट किए गए हुक से भी बदलें:
const { data, refetch: refetchDashboard } = useGetDashboardData();
useEffect(() => {
if (!user) return;
// Subscribe to realtime updates for the authenticated user's profile
const unsub = subscribe(getUserProfileRef(), (res) => {
if (res.data) {
setProfileData(res.data);
setOptimisticRole(null);
}
});
return () => unsub();
}, [user]);
अहम जानकारी
getUserProfileRef/getDashboardDataRef: अपने-आप जनरेट होने वाले फ़ंक्शन, जो GraphQL क्वेरी को एक्ज़ीक्यूट करने के लिए तैयार करते हैं. साथ ही, आपकी टेबल और व्यू के लिए तय किए गए स्ट्रिक्ट टाइप को सुरक्षित रखते हैं.subscribe: यह SQL Connect SDK टूल का एक ऐसा तरीका है जो क्वेरी को सुनता है. फ़िलहाल, कॉम्पोनेंट माउंट होने पर यह फ़ंक्शन सिर्फ़ डेटा फ़ेच करता है. हालांकि, बाद के चरण में हम बैकएंड को अपग्रेड करेंगे, ताकि डेटाबेस में बदलाव होने पर यह फ़ंक्शन अपने-आप ट्रिगर हो जाए!
- मार्केट पैनल (
components/MarketPanel.tsx): इसी तरह, MarketPanel कॉम्पोनेंट (components/MarketPanel.tsx) में, साइडबार बनाने के लिए एक साथ कई क्वेरी कॉल करने के लिए,TODOको बदला जा सकता है.
import { subscribe } from "@firebase/data-connect";
import { getDashboardDataRef, getEmojiSparklinesRef } from "@dataconnect/generated";
// Inside the MarketPanel component:
useEffect(() => {
// Subscribe to realtime updates for the main market dashboard data including top emojis and recent events
const unsub = subscribe(
getDashboardDataRef(),
(res) => {
if (res.data) setData(res.data);
},
(err) => console.error("Market Panel Realtime Error:", err)
);
return () => unsub();
}, []);
useEffect(() => {
// Subscribe to realtime price history updates to render emoji sparkline charts
const unsub = subscribe(
getEmojiSparklinesRef(),
(res) => {
if (res.data?.emojiSparklines) {
setSparklineRawData(res.data.emojiSparklines);
}
},
(err) => console.error("Global Sparklines Error:", err)
);
return () => unsub();
}, []);
- लीडरबोर्ड पेज (
app/leaderboard/page.tsx)
import { subscribe } from "@firebase/data-connect";
import { getTopTradersRef } from "@dataconnect/generated";
// Inside the Leaderboard component:
useEffect(() => {
// Subscribe to realtime updates for the global leaderboard ranking top traders by net worth
const unsubscribe = subscribe(
getTopTradersRef(),
(res) => {
if (res.data) setData(res.data);
setIsLoading(false);
},
(err) => {
console.error("Leaderboard Realtime Error:", err);
setIsLoading(false);
},
);
return () => unsubscribe();
}, []);
- इमोजी मोडल (
components/EmojiModal.tsx)
import { subscribe } from "@firebase/data-connect";
import {
getEmojiHistoryStatsRef,
getEmojiWhaleStatsRef,
} from "@dataconnect/generated";
// Inside the EmojiModal component:
useEffect(() => {
if (!emoji?.id) return;
setStatsLoading(true);
// Subscribe to realtime historical price and moving average statistics for the selected emoji
const unsub = subscribe(
getEmojiHistoryStatsRef({ emojiId: emoji.id }),
(res) => {
if (res.data) setStatsData(res.data);
setStatsLoading(false);
},
(err) => {
console.error("History Realtime Error:", err);
setStatsLoading(false);
},
);
return () => unsub();
}, [emoji?.id]);
useEffect(() => {
// Subscribe to realtime whale statistics to identify the top shareholder for the selected emoji
const unsub = subscribe(
getEmojiWhaleStatsRef(),
(res) => {
if (res.data) setWhaleData(res.data);
},
(err) => console.error("Whale Realtime Error:", err),
);
return () => unsub();
}, []);
इसे चलाकर देखें
क्वेरी को लागू होते हुए देखने के लिए, अपने वेब ऐप्लिकेशन को फिर से लोड करें. होम पेज और साइडबार पर अब इमोजी की सूची दिखती है. यह सूची, सीधे आपके PostgreSQL डेटाबेस से डेटा फ़ेच करती है.
6. उपयोगकर्ता के अपडेट और मार्केट ट्रांज़ैक्शन मैनेज करना
इस सेक्शन में, Firebase Authentication का इस्तेमाल करके उपयोगकर्ता के साइन-इन करने की सुविधा लागू की जाएगी. इससे Firebase SQL Connect में उपयोगकर्ता की प्रोफ़ाइलें (जैसे, उनका डिसप्ले नेम और जगह की जानकारी) अपडेट की जा सकेंगी. इसके अलावा, आपको SQL Connect के @transaction और @check डायरेक्टिव का इस्तेमाल करके, एटॉमिक और कई चरणों वाले मार्केट इवेंट को सुरक्षित तरीके से लागू करना होगा.
उपयोगकर्ता और जगह की जानकारी के कनेक्टर लागू करना
dataconnect/friendly-exchange/mutations.gql खोलें. उपयोगकर्ताओं को बनाने, अपडेट करने, और ढूंढने के लिए, यहां दिए गए म्यूटेशन जोड़कर TODO को बदलें:
# Upserts a user record using the Firebase Auth uid expression as the primary key
# Upsert (update or insert) a user's profile information
mutation UpsertUser($username: String!, $profileImage: String!)
@auth(level: USER) {
user_upsert(
data: {
id_expr: "auth.uid"
username: $username
profileImage: $profileImage
}
)
}
# Update a user's role
mutation UpdateUserRole($role: String!) @auth(level: USER) {
user_update(key: { id_expr: "auth.uid" }, data: { role: $role })
}
# Update a user's location
mutation UpdateUserLocation(
$city: String!
$latitude: Float!
$longitude: Float!
) @auth(level: USER) {
user_update(
key: { id_expr: "auth.uid" }
data: { city: $city, latitude: $latitude, longitude: $longitude }
)
}
# Trigger a new market event for an emoji
mutation TriggerEvent(
$emojiId: UUID!
$impact: Float!
$description: String!
$now: Timestamp!
) @auth(level: USER) {
event_insert(
data: {
userId_expr: "auth.uid"
emojiId: $emojiId
impact: $impact
description: $description
createdAt: $now
}
)
}
अहम जानकारी
id_expr: "auth.uid": यहauth.uidका इस्तेमाल करता है, जिसे सीधे तौर पर Firebase Authentication टोकन से उपलब्ध कराया जाता है. सर्वर-साइड पर इस प्रोसेस का आकलन करने से, यह पक्का किया जा सकता है कि कोई उपयोगकर्ता सिर्फ़ अपनी प्रोफ़ाइल का डेटा अपडेट कर सकता है. इससे सुरक्षा की एक मज़बूत लेयर जुड़ जाती है.
@transaction के साथ चेन लॉजिक
इसके बाद, आपको "मार्केट मेकर" लागू करना होगा. इसे एडमिन, मार्केट में होने वाली रैंडम गतिविधि को सिम्युलेट करने के लिए ट्रिगर कर सकता है. इसके लिए, हमें एक एटॉमिक ट्रांज़ैक्शन की ज़रूरत होती है, क्योंकि इसमें एक साथ इमोजी की कीमत अपडेट करना, इवेंट को लॉग करना, और सिस्टम के स्टॉक के मालिकाना हक को अपडेट करना होता है.
अपनी mutations.gql फ़ाइल में यह म्यूटेशन जोड़ें:
# Execute a market maker trade to adjust emoji price and shares
mutation MarketMakerTrade(
$emojiId: UUID!
$priceImpact: Float!
$shareDelta: Int!
$eventDesc: String!
$newPrice: Float!
)
@auth(
level: USER
insecureReason: "This operation is safe to expose to any user."
)
@transaction {
query @redact {
user(key: { id_expr: "auth.uid" })
@check(
expr: "this != null && this.role == 'ADMIN'",
message: "Access Denied: You must have the ADMIN role to deploy the Market Maker bot."
) {
role
}
}
stockOwnership_upsert(
data: {
userId: "system_market_maker"
emojiId: $emojiId
shares_update: { inc: $shareDelta }
}
)
emoji_update(
id: $emojiId
data: { currentPrice_update: { inc: $priceImpact }, trend: $priceImpact }
)
event_insert(
data: {
userId: "system_market_maker"
emojiId: $emojiId
impact: $priceImpact
description: $eventDesc
}
)
priceHistory_insert(data: { emojiId: $emojiId, price: $newPrice })
}
अहम जानकारी
@transaction: इससे यह पक्का किया जाता है कि डेटाबेस से जुड़ी सभी कार्रवाइयां (स्टॉक बढ़ाना, इमोजी की कीमत अपडेट करना, इवेंट लॉग करना) एक साथ पूरी हों या एक साथ फ़ेल हों.@check: यह एक ऐसा डायरेक्टिव है जो आगे बढ़ने से पहले किसी शर्त का आकलन करता है. यहां यह देखा जाता है कि पुष्टि किए गए उपयोगकर्ता काrole,'ADMIN'है या नहीं. अगर उपयोगकर्ता सिर्फ़ एक स्टैंडर्ड'USER'है, तो पूरा लेन-देन अस्वीकार कर दिया जाता है और उसे वापस कर दिया जाता है.@redact: यह क्वेरी के नतीजों (जैसे कि उपयोगकर्ता की भूमिका की जांच) को जवाब के पेलोड में क्लाइंट को वापस भेजने से रोकता है. इससे लेन-देन का जवाब साफ़ रहता है.
एसडीके टूल जनरेट करना
आपने GraphQL फ़ाइलों में नए म्यूटेशन तय किए हैं. इसलिए, आपको SDK जनरेटर चलाना होगा, ताकि आपका TypeScript फ़्रंटएंड इसे कॉल कर सके.
अपना टर्मिनल खोलें और यह कमांड चलाएं:
firebase dataconnect:sdk:generate
वेब ऐप्लिकेशन में म्यूटेशन को इंटिग्रेट करना
अपने वेब ऐप्लिकेशन में, जनरेट किए गए इन एसडीके म्यूटेशन को स्टैंडर्ड एसिंक फ़ंक्शन में रैप करें, ताकि गड़बड़ी का पता लगाया जा सके और यूज़र इंटरफ़ेस (यूआई) की सूचनाएं मैनेज की जा सकें.
lib/ExchangeService.tsx खोलें और रैपर फ़ंक्शन की समीक्षा करें. TODO ब्लॉक की जगह, यहां दिए गए कोड का इस्तेमाल करें:
import {
upsertUser,
updateUserLocation,
marketMakerTrade,
updateUserRole,
triggerMarketCrash,
} from "@dataconnect/generated";
// Upsert (update or insert) a user's profile information and log the event
export const executeUpsertUser = async (
username: string,
profileImage: string,
logEvent: (key: LogEventKey, params?: any) => void,
): Promise<void> => {
logEvent("UPSERT_USER_MUTATION", { username });
await upsertUser({ username, profileImage });
};
// Update a user's role and log the event
export const executeUpdateRole = async (
role: string,
logEvent: (key: LogEventKey, params?: any) => void
): Promise<void> => {
logEvent("UPDATE_USER_ROLE_MUTATION", { role });
await updateUserRole({ role });
};
// Update a user's city and geographic coordinates
export const executeUpdateLocation = async (
city: string,
latitude: number,
longitude: number,
): Promise<void> => {
await updateUserLocation({ city, latitude, longitude });
};
// Execute a random market maker trade and adjust an emoji's stock price
export const executeManualBotTrade = async (
randomEmoji: any,
username: string,
logEvent: (key: LogEventKey, params?: any) => void,
): Promise<{ isBuy: boolean; tradeAmount: number }> => {
logEvent("MARKET_MAKER_TRADE");
const isBuy = Math.random() > 0.5;
const tradeAmount = Number((Math.random() * (10 - 2) + 2).toFixed(2));
await marketMakerTrade({
emojiId: randomEmoji.id,
priceImpact: isBuy ? tradeAmount : -tradeAmount,
shareDelta: isBuy ? 10 : -10,
eventDesc: `Admin ${username} triggered market event: ${randomEmoji.symbol} went ${isBuy ? "up" : "down"} by $${tradeAmount.toFixed(2)}.`,
newPrice: Math.max(0.01, randomEmoji.currentPrice + (isBuy ? tradeAmount : -tradeAmount)),
});
return { isBuy, tradeAmount };
};
Triggering upsert on login: In app/src/components/Navbar.tsx, you can see how executeUpsertUser is called immediately after Firebase Authentication successfully signs a user in via Google Popup. This guarantees the SQL Connect database is synced with Firebase Auth.
See it in action
Now, click the Sign In button in the navbar. You can sign in using Firebase Authentication. After signing in:
- Navigate to your Profile and test out the Auto-Locate button. When you click Update Coordinates, the
UpdateUserLocationmutation will execute. - Open the Floating Control Panel (the purple icon in the bottom right corner).
- Click USER and switch your authorization level to ADMIN.
- Click Trigger random market activity. Because your role is now
'ADMIN', the@checkdirective passes, the@transactionexecutes, and you will instantly see the market prices update across your application!
7. Advanced operations with Native SQL
In this section, you will use Native SQL to execute complex Data Manipulation Language (DML) statements and leverage PostgreSQL-specific extensions.
While standard GraphQL and @views are ideal for strictly-typed CRUD and read-only operations, Native SQL provides execution-time flexibility. It allows you to use Common Table Expressions (CTEs) to chain multiple updates in a single database round-trip, and lets you query native PostgreSQL extensions directly.
Enable the PostGIS extension
Before we write geospatial queries, you need to enable the PostGIS extension on your Cloud SQL database.
- Navigate to the Google Cloud Console.
- Go to Cloud SQL -> select your provisioned instance -> click Cloud SQL Studio.
- Log into your database and execute the following command:
CREATE EXTENSION IF NOT EXISTS postgis;
Implement Native SQL Queries
Let's use Native SQL to find trending emojis near the user's physical location, and to calculate the top emojis per city using complex ranking.
- Open
dataconnect/friendly-exchange/queries.gql. - Add the following Native SQL queries using the
_selectfield:
# Get top trending emojis partitioned by user city using native SQL
query GetTopEmojisByCity
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
cityTrends: _select(
sql: """
WITH city_shares AS (
SELECT
u.city,
AVG(u.latitude) as latitude,
AVG(u.longitude) as longitude,
e.id as emoji_id,
e.symbol,
e.name,
SUM(so.shares) as total_shares,
RANK() OVER (PARTITION BY u.city ORDER BY SUM(so.shares) DESC) as rank
FROM stock_ownership so
JOIN "user" u ON so.user_id = u.id
JOIN emoji e ON so.emoji_id = e.id
WHERE u.city IS NOT NULL AND u.latitude IS NOT NULL AND so.shares > 0
GROUP BY u.city, e.id, e.symbol, e.name
)
SELECT city, latitude, longitude, emoji_id, symbol, name, total_shares
FROM city_shares
WHERE rank = 1
ORDER BY city ASC
"""
params: []
)
}
# Get trending emojis within a geographic radius using native SQL and PostGIS extension
query GetTrendingEmojisNearMe(
$userLng: Float!
$userLat: Float!
$radiusMeters: Float!
)
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
) {
regionalTrends: _select(
sql: """
SELECT
e.id,
e.symbol,
e.name,
e.current_price,
e.trend,
COUNT(so.shares) AS regional_holders,
SUM(so.shares) AS regional_shares
FROM emoji e
JOIN stock_ownership so ON so.emoji_id = e.id
JOIN "user" u ON u.id = so.user_id
WHERE u.latitude IS NOT NULL
AND u.longitude IS NOT NULL
AND so.shares > 0
AND ST_DWithin(
ST_MakePoint(u.longitude, u.latitude)::geography,
ST_MakePoint($1, $2)::geography,
$3
)
GROUP BY e.id, e.symbol, e.name, e.current_price, e.trend
ORDER BY regional_shares DESC
LIMIT 10
"""
params: [$userLng, $userLat, $radiusMeters]
)
}
Key Takeaways
_select: Executes a Data Query Language (DQL) statement returning a JSON array ([Any]).ST_DWithin: A native PostGIS function that calculates distances on a sphere. Native SQL allows you to use this without mapping complex geometry types into your GraphQL schema.params: Variables like$userLngare bound to the SQL string via positional parameters ($1,$2,$3), preventing SQL injection.
Implement Native SQL Mutations
When a user buys or sells a stock, the system must validate their funds, deduct the cost, add the shares, update the global emoji price, and log the history. Doing this across multiple standard mutations could lead to race conditions. Instead, we can use a CTE (WITH) to do this atomically in one Native SQL execution.
Open dataconnect/friendly-exchange/mutations.gql and replace the TODOs with the following Native SQL mutations:
# Buy shares of an emoji stock
mutation BuyStock($emojiId: UUID!, $amount: Int!, $isDiscounted: Boolean!)
@auth(level: USER) {
buyStock: _execute(
sql: """
WITH validated_params AS (
SELECT
$1::uuid AS emoji_id,
$2::int AS amount,
$3::boolean AS is_discounted,
$4::text AS user_id
),
target_emoji AS (
SELECT
e.id,
(e.current_price * (CASE WHEN vp.is_discounted THEN 0.5 ELSE 1.0 END) * vp.amount) AS total_cost
FROM emoji e
CROSS JOIN validated_params vp
WHERE e.id = vp.emoji_id
AND vp.amount > 0
AND vp.amount <= 100
),
deduct_funds AS (
UPDATE "user" u
SET points = u.points - te.total_cost
FROM target_emoji te, validated_params vp
WHERE u.id = vp.user_id AND u.points >= te.total_cost
RETURNING u.id
),
upsert_ownership AS (
INSERT INTO stock_ownership (user_id, emoji_id, shares)
SELECT vp.user_id, vp.emoji_id, vp.amount
FROM validated_params vp
WHERE EXISTS (SELECT 1 FROM deduct_funds)
ON CONFLICT (user_id, emoji_id) DO UPDATE
SET shares = stock_ownership.shares + EXCLUDED.shares
RETURNING stock_ownership.emoji_id
),
update_emoji AS (
UPDATE emoji e
SET
current_price = GREATEST(0.01, e.current_price + (e.current_price * 0.01 * vp.amount)),
trend = GREATEST(0.01, e.current_price + (e.current_price * 0.01 * vp.amount)) - e.current_price
FROM validated_params vp
WHERE e.id = vp.emoji_id AND EXISTS (SELECT 1 FROM deduct_funds)
RETURNING e.id, e.current_price, e.trend
)
INSERT INTO price_history (id, emoji_id, price, recorded_at)
SELECT gen_random_uuid(), ue.id, ue.current_price, NOW()
FROM update_emoji ue;
"""
params: [$emojiId, $amount, $isDiscounted, { _expr: "auth.uid" }]
)
}
# Sell shares of an emoji stock
mutation SellStock($emojiId: UUID!, $amount: Int!) @auth(level: USER) {
sellStock: _execute(
sql: """
WITH validated_params AS (
SELECT
$1::uuid AS emoji_id,
$2::int AS amount,
$3::text AS user_id
),
target_emoji AS (
SELECT
e.id,
(e.current_price * vp.amount) AS total_revenue,
GREATEST(0.01, e.current_price * POWER(0.99, vp.amount)) AS new_price
FROM emoji e
CROSS JOIN validated_params vp
WHERE e.id = vp.emoji_id
AND vp.amount > 0
AND vp.amount <= 100
),
check_shares AS (
SELECT so.user_id
FROM stock_ownership so
CROSS JOIN validated_params vp
WHERE so.user_id = vp.user_id
AND so.emoji_id = vp.emoji_id
AND so.shares >= vp.amount
),
add_funds AS (
UPDATE "user" u
SET points = u.points + te.total_revenue
FROM target_emoji te, validated_params vp
WHERE u.id = vp.user_id AND EXISTS (SELECT 1 FROM check_shares)
RETURNING u.id
),
update_ownership AS (
UPDATE stock_ownership so
SET shares = so.shares - vp.amount
FROM validated_params vp
WHERE so.user_id = vp.user_id
AND so.emoji_id = vp.emoji_id
AND EXISTS (SELECT 1 FROM check_shares)
AND EXISTS (SELECT 1 FROM add_funds)
),
update_emoji AS (
UPDATE emoji e
SET
current_price = te.new_price,
trend = te.new_price - e.current_price
FROM target_emoji te, validated_params vp
WHERE e.id = vp.emoji_id
AND EXISTS (SELECT 1 FROM check_shares)
AND EXISTS (SELECT 1 FROM add_funds)
RETURNING e.id, e.current_price, e.trend
)
INSERT INTO price_history (id, emoji_id, price, recorded_at)
SELECT gen_random_uuid(), ue.id, ue.current_price, NOW()
FROM update_emoji ue;
"""
params: [$emojiId, $amount, { _expr: "auth.uid" }]
)
}
Key Takeaways
_execute: Executes a Data Manipulation Language (DML) statement, such asUPDATE,INSERT, orDELETE.- Common Table Expressions (
WITH): Each block in the CTE depends on the previous one. For example,add_fundswill only execute ifcheck_sharesreturns a result. This handles the complex conditions completely within Postgres. - Context Injection:
{ _expr: "auth.uid" }injects the authenticated user's ID into the query directly on the server, enforcing security.
Generate the SDK
Because you have defined new queries and mutations in your GraphQL files, you must run the SDK generator so your TypeScript frontend can call it.
Open your terminal and run:
firebase dataconnect:sdk:generate
Integrate Native SQL in the web app
- Native SQL returns a flexible JSON payload rather than a strictly typed object. Because of this, it's essential to manually validate the returned data shape in your client code to handle the dynamic response.
- Execute Trades: In
lib/ExchangeService.tsx, we wrap the generatedbuyStockandsellStockSDKs. Notice how the return typesbuyResultandsellResultmust be manually validated as arrays, because_executereturns dynamic JSON data based on your specificRETURNINGclauses in the SQL strings. - Replace the empty
executeBuyStockandexecuteSellStockfunctions with your original complete code:
import { buyStock, sellStock, generateTradeHeadline, triggerEvent } from "@dataconnect/generated";
import { LogEventKey } from "./InspectorContext";
// Execute a stock purchase, validating limits and potentially generating an AI news headline for large trades
export const executeBuyStock = async (
emoji: any,
amount: number,
isDiscounted: boolean,
user: any,
logEvent: (key: LogEventKey, params?: any) => void,
): Promise<void> => {
const MAX_AMOUNT = 100;
if (!Number.isInteger(amount) || amount <= 0 || amount > MAX_AMOUNT) {
throw new Error(`Amount must be an integer between 1 and ${MAX_AMOUNT}.`);
}
const singleSharePrice = isDiscounted
? emoji.currentPrice * 0.5
: emoji.currentPrice;
const estimatedCost = singleSharePrice * amount;
const estimatedImpact = emoji.currentPrice * 0.05 * amount;
logEvent("BUY_STOCK_TRANSACTION", { amount, symbol: emoji.symbol });
const response = await buyStock({
emojiId: emoji.id,
amount: amount,
isDiscounted: isDiscounted,
});
const buyResult = response.data?.buyStock as any;
if (
!buyResult ||
buyResult === 0 ||
(Array.isArray(buyResult) && buyResult.length === 0)
) {
throw new Error(
"Transaction denied: Insufficient funds or price mismatch.",
);
}
const actualCost = Array.isArray(buyResult)
? buyResult[0].actual_cost
: estimatedCost;
const actualImpact = Array.isArray(buyResult)
? buyResult[0].actual_impact
: estimatedImpact;
// TODO: Optionally add a custom resolver to call AI to generate headline for this purchase
};
// Execute a stock sale, validating ownership and potentially generating an AI news headline for large trades
export const executeSellStock = async (
emoji: any,
amount: number,
ownedShares: number,
user: any,
logEvent: (key: LogEventKey, params?: any) => void,
): Promise<void> => {
const MAX_AMOUNT = 100;
if (!Number.isInteger(amount) || amount <= 0 || amount > MAX_AMOUNT) {
throw new Error(`Amount must be an integer between 1 and ${MAX_AMOUNT}.`);
}
if (amount > ownedShares) {
throw new Error(
"INSUFFICIENT SHARES: You cannot sell more shares than you own.",
);
}
const estimatedRevenue = emoji.currentPrice * amount;
const dropRatePerShare = 0.05;
const targetPrice =
emoji.currentPrice * Math.pow(1 - dropRatePerShare, amount);
const estimatedImpact = Math.max(0.01, targetPrice) - emoji.currentPrice;
logEvent("SELL_STOCK_TRANSACTION", { amount, symbol: emoji.symbol });
const response = await sellStock({
emojiId: emoji.id,
amount: amount,
});
const sellResult = response.data?.sellStock as any;
if (
!sellResult ||
sellResult === 0 ||
(Array.isArray(sellResult) && sellResult.length === 0)
) {
throw new Error("Transaction denied: Insufficient shares.");
}
const actualRevenue = Array.isArray(sellResult)
? sellResult[0].actual_revenue
: estimatedRevenue;
const actualImpact = Array.isArray(sellResult)
? sellResult[0].actual_impact
: estimatedImpact;
// TODO: Optionally add a custom resolver to call AI to generate headline for this sale
};
Query Geospatial Data (Local Radar): In app/src/components/LocalRadar.tsx, we subscribe to the getTrendingEmojisNearMeRef query. The dynamic JSON array from the _select execution maps directly to the UI list, utilizing PostGIS's distance calculations.
import { subscribe } from "@firebase/data-connect";
import { getTrendingEmojisNearMeRef } from "@dataconnect/generated";
// ... inside the component
useEffect(() => {
if (!location) return;
setIsLoadingTrends(true);
// Subscribe to realtime updates for trending emojis within a 50km radius
const unsub = subscribe(
getTrendingEmojisNearMeRef({
userLat: location.lat,
userLng: location.lng,
radiusMeters: 50000, // 50km
}),
(res) => {
if (res.data) setLocalData(res.data);
setIsLoadingTrends(false);
},
(err) => {
console.error("Local Radar Realtime Error:", err);
setIsLoadingTrends(false);
},
);
return () => unsub();
}, [location?.lat, location?.lng]);
Query Geospatial Data (Global Assets Map): In app/src/app/map/page.tsx (the Insights Page), we use Native SQL's complex window functions (RANK() OVER) to find the single most popular emoji for every city in the database.
import { subscribe } from "@firebase/data-connect";
import { getTopEmojisByCityRef, getTrendingEmojisNearMeRef, getUserProfileRef } from "@dataconnect/generated";
// ... inside the component
useEffect(() => {
// Subscribe to realtime updates for the authenticated user's profile and stock ownership
const unsub = subscribe(getUserProfileRef(), (res) => {
if (res.data) setProfileData(res.data);
});
return () => unsub();
}, []);
useEffect(() => {
// Subscribe to realtime updates for top trending emojis partitioned by user city
const unsub = subscribe(getTopEmojisByCityRef(), (res) => {
if (res.data) setCityData(res.data);
});
return () => unsub();
}, []);
useEffect(() => {
setRadarLoading(true);
// Subscribe to realtime updates for trending emojis within a specified geographic radius
const unsub = subscribe(
getTrendingEmojisNearMeRef({
userLat: coords.lat,
userLng: coords.lng,
radiusMeters: radiusKm * 1000,
}),
(res) => {
if (res.data) setRadarData(res.data);
setRadarLoading(false);
},
);
return () => unsub();
}, [coords.lat, coords.lng, radiusKm]);
See it in action
- In your browser, navigate to the Geo page from the top navigation bar.
- If your location is correctly set in your Profile, the Global Top Assets map will ping the
GetTopEmojisByCitynative query to drop pins on cities with high trade volumes. - Click Scan Local Network. The
Local Radar Scannerwill ask for your browser's location and ping theGetTrendingEmojisNearMenative query, utilizing PostGIS to find the top assets specifically traded within 50km of your coordinates! - Navigate to the Home page or Profile page and purchase some assets to see your balance deduct and the emoji price update automatically via your atomic
_executequeries.
8. Realtime subscriptions and caching
In the previous section, we used the subscribe() method in our React components to fetch data. While that successfully retrieved the initial state, a true stock exchange needs to feel alive. If another user buys a massive amount of emoji stock, your screen should update instantly.
This is where Firebase SQL Connect's Realtime features come in.
What is Realtime and how does it work?
Realtime support allows your application to receive proactive notifications from the server whenever data your app is using has been updated.
Here is the underlying mechanism:
- Trigger (
@refresh): You tell the SQL Connect backend which specific mutations should trigger a data refresh for a given query. - Broadcast: When one of those mutations executes (e.g., someone runs
BuyStock), the server proactively broadcasts a realtime notification to any connected clients listening to that query. - Cache Update: When the notification arrives, the JS SDK treats it just like an ad-hoc query execution. The local cache is instantly updated with the new data.
- UI Reactivity: The SDK automatically fires the
onNextcallbacks for all active subscribers, causing your React state to update and your UI to re-render "in real time".
Add @refresh triggers to your queries
To enable this on the backend, we need to add the @refresh directive to our queries.
- Open
dataconnect/friendly-exchange/queries.gql. - Update your existing queries by attaching
@refreshdirectives for every market-altering mutation. For example, updateGetDashboardDataandGetUserProfile:
# Get dashboard data including top emojis by price and recent market events
query GetDashboardData
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
)
@refresh(onMutationExecuted: { operation: "BuyStock" })
@refresh(onMutationExecuted: { operation: "SellStock" })
@refresh(onMutationExecuted: { operation: "TriggerEvent" })
@refresh(onMutationExecuted: { operation: "MarketMakerTrade" }) {
emojis(orderBy: [{ currentPrice: DESC }]) {
id
symbol
name
description
currentPrice
trend
}
events(orderBy: [{ createdAt: DESC }], limit: 15) {
id
description
impact
createdAt
user {
username
profileImage
}
emoji {
symbol
}
}
}
# Get current authenticated user profile and their stock ownership using auth.uid
query GetUserProfile
@auth(level: USER)
@refresh(onMutationExecuted: { operation: "BuyStock" })
@refresh(onMutationExecuted: { operation: "SellStock" })
@refresh(onMutationExecuted: { operation: "UpdateUserLocation" })
@refresh(onMutationExecuted: { operation: "UpdateUserRole" }) {
user(id_expr: "auth.uid") {
points
username
profileImage
role
stockOwnerships_on_user {
shares
emoji {
id
symbol
currentPrice
name
}
}
city
latitude
longitude
}
}
Key Takeaways
@refresh(onMutationExecuted: ...): Instructs the server to re-evaluate this query and push new data to subscribers whenever the specified mutation occurs.
Generate the SDK
Because you have defined new queries and mutations in your GraphQL files, you must run the SDK generator so your TypeScript frontend can call it.
Open your terminal and run:
firebase dataconnect:sdk:generate
Handle Realtime Subscriptions in the Web App
We already laid the groundwork for this in the previous section by using the subscribe method. Let's look closer at how the generated SDK handles this in React.
If you open app/src/app/page.tsx (the Home page), you will see the useEffect hook managing the dashboard data:
import { subscribe } from "@firebase/data-connect";
import { getDashboardDataRef } from "@dataconnect/generated";
// ... inside the component
useEffect(() => {
const queryRef = getDashboardDataRef();
// The subscribe function registers the QueryRef and callbacks
const unsubscribe = subscribe(
queryRef,
(res) => {
// onNext: Fires initially, AND whenever a @refresh trigger occurs
if (res.data) setDashboardData(res.data);
setIsDashboardLoading(false);
},
(err) => {
// onError: Handles any server or permission errors
console.error("Dashboard Realtime Error:", err);
setIsDashboardLoading(false);
}
);
// onComplete/Cleanup: Unregisters the callbacks when the component unmounts
return () => unsubscribe();
}, [user]);
Key Takeaways
subscribe(queryRef, onNext, onError): Enables Realtime notifications for the specificQueryRef.unsubscribe(): Callingsubscribereturns a cleanup function. It is critical to return this in youruseEffectso that when the component unmounts (e.g., the user navigates away), the subscription is canceled and memory leaks are prevented.- Caching Efficiency: If multiple components subscribe to the same query (like
GetDashboardData), the SDK shares the cached result. When a Realtime notification arrives, the cache updates once, and all active subscribers are notified automatically.
See it in action
Because you've added @refresh to your backend and subscribe to your frontend, your app is now fully reactive.
- Open your web app in two separate browser windows side-by-side.
- In one window, purchase a few shares of an emoji.
- Watch the second window—without refreshing the page, you will instantly see the emoji's price increase!
9. Conclusion
Congratulations, you've successfully built and deployed a realtime, highly complex trading platform directly on top of PostgreSQL using Firebase SQL Connect!
By utilizing SQL Connect, you were able to:
- Define a strictly-typed GraphQL schema that maps directly to PostgreSQL.
- Enforce granular, row-level security using Firebase Authentication and @auth directives.
- Leverage advanced Native SQL to query geospatial data with PostGIS and write atomic market transactions via CTEs.
- Make your entire application reactive using the @refresh directive for realtime subscriptions.
- Seamlessly generate frontend SDKs to keep your client code synced with your database.
If you want to play with your own market data, feel free to insert your own mock emojis, locations, and pricing histories using the Firebase SQL Connect extension by mimicking the .gql seed files, or add them through the SQL Connect execution pane in VS Code.
10. Deploy to Cloud
Now that you've worked through the local development iteration, it's time to deploy your schema, data, and queries to the server. This can be done using the Firebase SQL Connect VS Code extension or the Firebase CLI.
Set up Firebase Authentication in your Firebase project
- Set up Firebase Authentication with Google Sign-In.
- (Optional) Allow domains for Firebase Authentication using the Firebase console (for example,
http://127.0.0.1).- In the Authentication settings, go to Authorized Domains.
- Click "Add Domain" and include your local domain in the list.
Enable required PostgreSQL Extensions
Because this app utilizes PostgreSQL extensions for vector search and location tracking, you must manually enable them on your provisioned Cloud SQL instance before deploying your schema.
- Navigate to the Google Cloud Console.
- Go to Cloud SQL -> select your provisioned instance -> click Cloud SQL Studio.
- Log into your database and execute the following commands:
# Required for the Geo Map page
CREATE EXTENSION IF NOT EXISTS postgis;
# Required for Vector Search
CREATE EXTENSION IF NOT EXISTS "vector";
# Required for automatic Vector Search embedding generation
CREATE EXTENSION IF NOT EXISTS "google_ml_integration";
Build your web app for hosting
Back in VS Code, ensure you have placed your firebaseConfig variables in lib/firebase.tsx (as done in the setup section).
Next, guarantee that your frontend is using the latest generated hooks by running:
firebase dataconnect:sdk:generate
Then, build the React web app for hosting deployment:
npm run build
Deploy with the Firebase CLI
In dataconnect/dataconnect.yaml, ensure that your instance ID, database, and service ID match your actual Google Cloud project identifiers, and use the v1 specification:
specVersion: v1
serviceId: your-project-id-service
location: us-west4
schemas:
- source: ./schema
datasource:
postgresql:
database: your-project-id-database
cloudSql:
instanceId: your-project-id-instance
connectorDirs:
- ./friendly-exchange
In your terminal, run the following command to deploy:
firebase deploy --only dataconnect,hosting
For updates or refactors, run this command to compare your schema changes:
firebase dataconnect:sql:diff
If the changes are acceptable, apply them with:
firebase dataconnect:sql:migrate
Your Cloud SQL for PostgreSQL instance will be updated with the final deployed schema and data. You should now be able to see your app live at your-project.web.app/.
Learn more
11. Optional: Vector search with Firebase SQL Connect (billing required)
In this section, you'll enable vector search in your emoji exchange using Firebase SQL Connect. This feature allows for semantic, content-based searches, such as finding emojis that match a vibe or concept using vector embeddings.
This step requires that you completed the last step of this codelab to deploy to Google Cloud.
Update the schema to include embeddings for a field
In dataconnect/schema/schema.gql, add the descriptionEmbedding field to your Emoji table. Replace your existing Emoji type with this updated version:
# Emojis
# emoji-stockOwnership is a one-to-many relationship, emoji-priceHistory is a one-to-many relationship
# Implements @searchable directives for full-text search
# Optional: implements Vector type for semantic search
type Emoji @table {
id: UUID! @default(expr: "uuidV4()")
symbol: String!
name: String! @searchable
tags: [String!]
description: String! @searchable
descriptionEmbedding: Vector @col(size: 768)
currentPrice: Float! @default(value: 10.0)
trend: Float! @default(value: 0.0)
}
Key Takeaways
descriptionEmbedding: Vector @col(size: 768): This field stores the semantic embeddings of your emoji descriptions, enabling vector-based content search in your app.
Add a vector search query
In dataconnect/friendly-exchange/queries.gql, add the following query to perform vector searches:
# Search emoji descriptions using Vertex AI embeddings
query VectorSearchEmojis($query: String!)
@auth(
level: PUBLIC
insecureReason: "This operation is safe to expose to the public."
)
@refresh(onMutationExecuted: { operation: "BuyStock" })
@refresh(onMutationExecuted: { operation: "SellStock" })
@refresh(onMutationExecuted: { operation: "TriggerEvent" })
@refresh(onMutationExecuted: { operation: "MarketMakerTrade" }) {
emojis_descriptionEmbedding_similarity(
compare_embed: { model: "text-multilingual-embedding-002", text: $query }
method: COSINE
within: 2
limit: 15
) {
id
symbol
name
description
currentPrice
trend
_metadata {
distance
}
}
}
Key Takeaways:
compare_embed: Specifies the embedding model (text-multilingual-embedding-002) and the input text ($query) for comparison.method: Specifies the similarity method (COSINE), measuring the cosine similarity between the vectors.within: Limits the search to emojis with a distance of 2 or less, focusing on close content matches.
Generate the SDK
Because you have defined new queries and mutations in your GraphQL files, you must run the SDK generator so your TypeScript frontend can call it.
Open your terminal and run:
firebase dataconnect:sdk:generate
Activate Vertex AI and re-deploy
- Follow the prerequisites guide to set up Vertex AI APIs from Google Cloud. This step is essential to support the embedding generation.
- Re-deploy your schema to activate
pgvectorand vector search by runningfirebase deploy --only dataconnector clicking "Deploy to Production" using the Firebase SQL Connect VS Code extension.
Populate the database with embeddings
- Open the
dataconnectfolder in VS Code. - Click Run (Production) in
optional_vector_seed.gqlto populate your deployed database with the 768-dimensional embeddings for the emojis.
Implement the vector search function in your app
Now that the schema and query are set up, integrate the vector search into your app's frontend.
In app/src/app/page.tsx (your Home component), review the useEffect that listens to the search input and swaps dynamically between full-text search and vector search based on the user's selected searchMode:
import { subscribe } from "@firebase/data-connect";
import {
getDashboardDataRef,
searchEmojisRef,
vectorSearchEmojisRef, // <-- Add this!
getChronologicalTickerRef,
getUserProfileRef,
} from "@dataconnect/generated";
// Inside Home component, find the search useeffect
useEffect(() => {
if (!debouncedSearch) {
setSearchData(null);
return;
}
let unsubscribe: () => void;
if (searchMode === "TEXT") {
// Subscribe to realtime full-text search results for emojis based on user input
unsubscribe = subscribe(
searchEmojisRef({ query: debouncedSearch }),
(res) => {
if (res.data) setSearchData(res.data.emojis_search);
setIsSearchLoading(false);
},
(err) => {
console.error("Text Search Error:", err);
setIsSearchLoading(false);
},
);
} else {
// Subscribe to realtime vector search results using semantic similarity for emojis based on user input
unsubscribe = subscribe(
vectorSearchEmojisRef({ query: debouncedSearch }),
(res) => {
if (res.data)
setSearchData(res.data.emojis_descriptionEmbedding_similarity);
setIsSearchLoading(false);
},
(err) => {
console.error("Vector Search Error:", err);
setIsSearchLoading(false);
},
);
}
return () => {
if (unsubscribe) unsubscribe();
};
}, [debouncedSearch, searchMode]);
See it in action
Navigate to the search bar on your app's homepage. Type in abstract phrases like "happy", "nature", or "technology". Toggle the search mode from TEXT to VECTOR and notice how the results shift from exact string matches to contextual, semantic matches returned directly from Vertex AI and PostgreSQL!
12. Optional: Custom Resolvers with Vertex AI (billing required)
10:00
By writing Custom Resolvers, you can extend Firebase SQL Connect to support other data sources and combine them into your unified GraphQL schema. In this section, you'll write a Firebase Cloud Function that uses Vertex AI (Gemini) to generate a satirical financial news headline whenever a user makes a large trade, and expose that function through SQL Connect.
Initialize the custom resolver
Instead of creating all the boilerplate files manually, the Firebase CLI has a built-in generator for custom resolvers.
Open your terminal in the root of your project and run:
firebase init dataconnect:resolver
When prompted by the CLI:
- Enter
generateTradeHeadlineas the name for your custom resolver. - Select TypeScript to generate the example implementation.
The CLI will automatically create a new dataconnect/schema_generateTradeHeadline/schema.gql file, initialize a functions directory with sample code, and link the resolver in your dataconnect.yaml configuration!
Define the custom resolver schema
Next, you need to define the exact shape of your custom endpoint using a GraphQL schema.
Open the newly generated dataconnect/schema_generateTradeHeadline/schema.gql file and replace its contents with the following code:
# Custom resolver fields can be defined on root Query and Mutation types.
type Mutation {
# This field will be backed by your Cloud Function.
generateTradeHeadline(
emojiSymbol: String!
emojiName: String!
username: String!
tradeAmount: Int!
tradeCost: Float!
tradeType: String!
): String!
}
Key Takeaways:
- By placing this inside the root
type Mutation, you are telling SQL Connect that this operation might have side-effects (like calling an AI API) rather than just reading data.
Implement the custom resolver logic
Next, implement your resolver using Cloud Functions. Under the hood, you are creating a GraphQL server; however, Cloud Functions provides a helper method, onGraphRequest, that handles the boilerplate so you only need to write the core logic.
Open your Firebase Functions file (functions/src/index.ts), which the CLI generated for you. Replace the entire file with the Gemini API implementation:
import { setGlobalOptions } from "firebase-functions";
import {
FirebaseContext,
onGraphRequest,
} from "firebase-functions/dataconnect/graphql";
import { initializeApp, getApps } from "firebase-admin/app";
import { GoogleGenAI } from "@google/genai";
setGlobalOptions({
maxInstances: 10,
region: "us-west4",
});
if (getApps().length === 0) {
initializeApp();
}
const ai = new GoogleGenAI({
vertexai: true,
project: process.env.GCLOUD_PROJECT || "your-project-id",
location: process.env.GCLOUD_LOCATION || "us-west4",
});
const headlineOpts = {
// Points to the schema you defined earlier
schemaFilePath: "dataconnect/schema_generateTradeHeadline/schema.gql",
resolvers: {
mutation: {
// Generate a satirical financial news headline for a stock trade using Vertex AI
async generateTradeHeadline(
_parent: unknown,
args: Record<string, unknown>,
_contextValue: FirebaseContext,
_info: unknown,
): Promise<string> {
const {
emojiSymbol,
emojiName,
username,
tradeAmount,
tradeCost,
tradeType,
} = args;
try {
const prompt = `You are a hype-driven, satirical financial news bot.
A user named '${username}' just executed a massive ${tradeType} of ${tradeAmount} shares of ${emojiSymbol} (${emojiName}) for $${tradeCost}.
Write a single, punchy, dramatic news headline (under 12 words) about this market move, use puns wherever possible, but don't round or exagerate the numbers. Include the asset symbol.`;
const response = await ai.models.generateContent({
model: "gemini-2.5-flash-lite",
contents: prompt,
});
if (!response.text) {
throw new Error("No text returned from Vertex AI");
}
return response.text.trim();
} catch (error) {
console.error("Vertex AI generation failed:", error);
return `BREAKING: Massive ${tradeType} detected on ${emojiSymbol}! Market reacting.`;
}
},
},
},
};
export const generateTradeHeadline = onGraphRequest(headlineOpts);
अहम जानकारी:
onGraphRequest: यह Firebase Functions का एक खास रैपर है. यह Cloud Function को SQL Connect Custom Resolver स्कीमा से मैप करता है.args: GraphQL म्यूटेशन से पास किए गए आर्ग्युमेंट, यहां अपने-आप टाइप हो जाते हैं और निकाले जाते हैं, ताकि उन्हें Gemini के प्रॉम्प्ट में डाला जा सके.
अपने कनेक्टर में म्यूटेशन जोड़ना
कस्टम रिज़ॉल्वर लॉजिक मौजूद होने के बाद, इसे अपने ऐप्लिकेशन के कनेक्टर के ज़रिए दिखाएं, ताकि फ़्रंटएंड इसे कॉल कर सके.
dataconnect/friendly-exchange/mutations.gql खोलें और म्यूटेशन जोड़ें:
# Generate an AI headline for a stock trade
mutation GenerateTradeHeadline(
$emojiSymbol: String!
$emojiName: String!
$username: String!
$tradeAmount: Int!
$tradeCost: Float!
$tradeType: String!
)
@auth(
level: USER
insecureReason: "This operation is safe to expose to any authenticated user."
) {
aiHeadline: generateTradeHeadline(
emojiSymbol: $emojiSymbol
emojiName: $emojiName
username: $username
tradeAmount: $tradeAmount
tradeCost: $tradeCost
tradeType: $tradeType
)
}
एसडीके टूल को डिप्लॉय और जनरेट करना
कस्टम रिज़ॉल्वर, Cloud Functions के ज़रिए काम करते हैं. इसलिए, एंडपॉइंट को चालू करने के लिए, आपको अपने फ़ंक्शन को Google Cloud पर डिप्लॉय करना होगा.
अपना टर्मिनल खोलें और फ़ंक्शन को डिप्लॉय करें:
firebase deploy --only functions
डप्लॉय करने के बाद, नया एआई म्यूटेशन शामिल करने के लिए, फ़्रंटएंड एसडीके जनरेट करें:
firebase dataconnect:sdk:generate
वेब ऐप्लिकेशन में एआई रिज़ॉल्वर को इंटिग्रेट करना
चलिए, इसे इस तरह से सेट अप करते हैं कि 10 या उससे ज़्यादा शेयर का कोई भी कारोबार होने पर, ब्रेकिंग न्यूज़ की सूचना ट्रिगर हो जाए!
lib/ExchangeService.tsx खोलें. सबसे पहले, पक्का करें कि आपने सबसे ऊपर generateTradeHeadline और triggerEvent इंपोर्ट किए हों:
import {
buyStock,
sellStock,
generateTradeHeadline,
triggerEvent
} from "@dataconnect/generated";
इसके बाद, स्क्रोल करके अपने executeBuyStock फ़ंक्शन के सबसे नीचे जाएं. साथ ही, फ़ंक्शन खत्म होने से ठीक पहले, TODO को एआई ट्रिगर ब्लॉक से बदलें:
// ... (existing executeBuyStock code)
const actualImpact = Array.isArray(buyResult)
? buyResult[0].actual_impact
: estimatedImpact;
if (amount >= 10 && user) {
setTimeout(() => {
logEvent("GENERATE_HEADLINE_RESOLVER");
}, 2000);
const headlineResult = await generateTradeHeadline({
emojiSymbol: emoji.symbol,
emojiName: emoji.name,
username: user.displayName || "Anonymous Whale",
tradeAmount: amount,
tradeCost: actualCost.toFixed(2),
tradeType: "BUY",
});
await triggerEvent({
emojiId: emoji.id,
impact: actualImpact.toFixed(2),
description: `GEMINI REPORT: ${headlineResult.data?.aiHeadline}`,
now: new Date().toISOString(),
});
}
};
executeSellStock फ़ंक्शन के सबसे नीचे, ठीक यही काम करें:
// ... (existing executeSellStock code)
const actualImpact = Array.isArray(sellResult)
? sellResult[0].actual_impact
: estimatedImpact;
if (amount >= 10 && user) {
const headlineResult = await generateTradeHeadline({
emojiSymbol: emoji.symbol,
emojiName: emoji.name,
username: user.displayName || "Anonymous Whale",
tradeAmount: amount,
tradeCost: actualRevenue.toFixed(2),
tradeType: "SELL",
});
await triggerEvent({
emojiId: emoji.id,
impact: actualImpact.toFixed(2),
description: `GEMINI REPORT: ${headlineResult.data?.aiHeadline}`,
now: new Date().toISOString(),
});
}
};
इसे चलाकर देखें
- अपने वेब ऐप्लिकेशन को फिर से लोड करें.
- पक्का करें कि आपने साइन इन किया हो और आपके पास ज़रूरी मुद्रा हो.
- कोई इमोजी चुनें और एक बार में 10 या उससे ज़्यादा शेयर खरीदें.
- अपने डैशबोर्ड की दाईं ओर मौजूद ग्लोबल मार्केट टिकर देखें. कुछ ही सेकंड में, आपको Gemini से जनरेट की गई व्यंग्यात्मक खबर की कस्टम हेडलाइन दिखेगी!