paint-brush
GraphQL Yatiñanakaj Nivelar: Chiqpach Tiempo Suscripcionesukata@johnjvester
477 ullart’awinaka
477 ullart’awinaka

GraphQL Yatiñanakaj Nivelar: Chiqpach Tiempo Suscripciones

ukata John Vester10m2024/09/18
Read on Terminal Reader

Sinti jaya pachanakawa; Uñxatt’añataki

Mä juk’a manqhar ch’allt’asim chiqpach pachan datos suscripciones ukanakat yatxatañataki GraphQL apnaqasa, ukhamat automáticamente servidor-side ukan machaq uñstawinakap katuqañataki, mä WebSocket apnaqirin yanapt’apampi.
featured image - GraphQL Yatiñanakaj Nivelar: Chiqpach Tiempo Suscripciones
John Vester HackerNoon profile picture

Jichhax mä qawqha maranakaw marcos, productos ukat servicios ukanakar uñt’ayañ yant’awayta, ukax tecnólogos ukanakarux propiedad intelectual ukan valoracionap jilxatayañanx ch’amanchañapatakiw yanapt’i. Akax nayatakix mä suma thakhiw sarantaskakiwa, jan uñt’at yatiqañ utanakamp phuqt’ata.


Nayan ingenierox jichhakiw jiskt’asiwayi, mä situación utjiti kawkhantix mä secundario beneficio jikxatañax mä utjki uka concepto ukatakix nayraqat arsuwayta. Mä arunxa, ¿yaqha askinak uñt’ayasmati, ukax pachpa nivel de impacto ukampiw uñt’ayasispa, kunjamatix nayrax awk taykan solución original uñt’atäki ukhama?


Aka qillqatatakix GraphQL ukar juk’amp manqhar ch’allt’añ munta, kuntix jikxatkta uk uñjañataki.


Nayan “ Kunapachatix REST ukar samart’añ pachax purinxi ” qillqatanx kunjams chiqpach pachan escenarios ukanakax utji kunapachatix GraphQL ukax mä servicio RESTful ukar sipanx juk’amp askiwa uka tuqitw arsuwayta. Kunjams mä GraphQL API lurañax ukat uñstayañax Apollo Server uka apnaqañ tuqitw sarnaqapxta.


Aka arktañ post ukanx GraphQL ukan yatiñanakax nivelar uñt’ayañ amtasta, suscripciones ukan sarnaqasa, chiqpach pachan yatiyawinak apsuñataki. Ukhamarakiw mä WebSocket servicio lurañäni, suscripciones ukanakar manq’añataki.

Recap: Cliente 360 Uñstayaña Caso

Nayrir qillqatajax mä Customer 360 apnaqañ tuqitw uñt’ayasi, kawkhantix patrones de mi negocio ficcional ukax aka datos apthapiwinak uñjapxi:


  • Clientenakan yatiyawipa
  • Dirección ukan yatiyawipa
  • Uñt’ayasiñ thakhinaka
  • Atributos de crédito ukanaka


Mä jach’a atipt’awix GraphQL apnaqañanx mä sapa GraphQL mayiwix taqi kunatix wakiski ukanak mä aljirin token (identidad única) ukatak apsuñapawa.


 type Query { addresses: [Address] address(customer_token: String): Address contacts: [Contact] contact(customer_token: String): Contact customers: [Customer] customer(token: String): Customer credits: [Credit] credit(customer_token: String): Credit }


Mä RESTful uñakipañampi apnaqañaxa mä sapa (360) uñjawi aljiriru apsuñatakixa walja mayiwinakampi jaysawinakampi ch’ukuñawa wakisispa. GraphQL ukax mä solución ukaw juk’amp suma irnaqañapatak churarakistu.

Nivel Up amtanaka

Kawkïr jakäwins nivelar puriñatakikix machaq amtanakaruw puriñapa. Nayan pachpa amtanakajatakix akanx akax akham sañ muni:


  • GraphQL ukan suscripción valor propuesta ukar amuyaña ukat phuqhaña.
  • Mä WebSocket phuqhawi apnaqaña mä GraphQL suscripción manq’añataki.


GraphQL ukan jiskt’awinaka ukat mutaciones ukanakat suscripciones apnaqañax wali askiwa, kunawsatix aka condiciones ukanakax phuqhatäki ukhaxa:


  • Jisk’a, jilxatir mayjt’awinaka jach’a yänakaru
  • Pisi latencia, chiqpach pachan machaq uñstawinaka (kunjamakitix mä aplicación de chat) .


Ukax wali askiw kunatix GraphQL ukan suscripciones ukar phuqhañax janiw jisk’akïkiti. Janiw servidor subyacente ukakix machaqar tukuyañakiti, jan ukasti aplicación consumidor ukax mä juk’a rediseño ukhamarakiw munasini.


Wali askiwa, caso de uso ukax jiwasan Cliente 360 uñacht’äwimp arktasktan ukax suscripciones ukanakatakix wali askiwa. Ukhamaraki, mä WebSocket uñakipañ phuqhachañäni uka suscripciones ukanakar aprovechañataki.


Kunjamatix nayrjax ukhamarakiw nayrar sartasax Apolo apnaqañax sarantaskakini.

Nivelación Ukax Suscripciones Creds ukampiw lurasi

Nayraqatxa, Apollo GraphQL servidor ukamp suscripciones ukar yanapt’añatakix wakiskir bibliotecas ukanakaw utt’ayañasa:


 npm install ws npm install graphql-ws @graphql-tools/schema npm install graphql-subscriptions


Uka yänakax utt’ayatawa, nayax index.ts ukar nayrïr imañ utat machaqar tukuyañaruw ch’amanchawayta, ukhamat typedefs constante ukar jilxatayañataki:


 type Subscription { creditUpdated: Credit }


Ukhamarakiw mä constante uñstayawaytxa mä machaq instancia PubSub ukar uñstayañataki ukatx mä suscripción de muestra ukham lurawayta ukax qhipat apnaqañäni:


 const pubsub = new PubSub(); pubsub.publish('CREDIT_BALANCE_UPDATED', { creditUpdated: { } });


Nayax utjki uka askichirinakaruw q’umachawayta ukatx mä machaq Subscription ukaruw yapxatta aka machaq apnaqañ tuqitxa:


 const resolvers = { Query: { addresses: () => addresses, address: (parent, args) => { const customer_token = args.customer_token; return addresses.find(address => address.customer_token === customer_token); }, contacts: () => contacts, contact: (parent, args) => { const customer_token = args.customer_token; return contacts.find(contact => contact.customer_token === customer_token); }, customers: () => customers, customer: (parent, args) => { const token = args.token; return customers.find(customer => customer.token === token); }, credits: () => credits, credit: (parent, args) => { const customer_token = args.customer_token; return credits.find(credit => credit.customer_token === customer_token); } }, Subscription: { creditUpdated: { subscribe: () => pubsub.asyncIterator(['CREDIT_BALANCE_UPDATED']), } } };


Ukatx configuración de servidor ukar refactorizawayta ukatx diseño de suscripción ukar uñt’ayawayta:


 const app = express(); const httpServer = createServer(app); const wsServer = new WebSocketServer({ server: httpServer, path: '/graphql' }); const schema = makeExecutableSchema({ typeDefs, resolvers }); const serverCleanup = useServer({ schema }, wsServer); const server = new ApolloServer({ schema, plugins: [ ApolloServerPluginDrainHttpServer({ httpServer }), { async serverWillStart() { return { async drainServer() { serverCleanup.dispose(); } }; } } ], }); await server.start(); app.use('/graphql', cors(), express.json(), expressMiddleware(server, { context: async () => ({ pubsub }) })); const PORT = Number.parseInt(process.env.PORT) || 4000; httpServer.listen(PORT, () => { console.log(`Server is now running on http://localhost:${PORT}/graphql`); console.log(`Subscription is now running on ws://localhost:${PORT}/graphql`); });


Cliente-driven actualizaciones ukar uñtasit lurañatakix aka lurawiw lurawayta, ukhamat saldo de crédito ukax sapa phisqa segundos ukjat 50 dólares ukjam jilxatayañataki, kunawsatix servicio ukax apnaqaski ukhaxa. Mä kutix saldox 10.000 dólares límite de crédito ukar purinxi (jan ukax jilt’ki) ukhax saldox 2.500 dólares ukjaruw kutt’ayawayta, mä saldo payllañ luraskir uñtasita.


 function incrementCreditBalance() { if (credits[0].balance >= credits[0].credit_limit) { credits[0].balance = 0.00; console.log(`Credit balance reset to ${credits[0].balance}`); } else { credits[0].balance += 50.00; console.log(`Credit balance updated to ${credits[0].balance}`); } pubsub.publish('CREDIT_BALANCE_UPDATED', { creditUpdated: credits[0] }); setTimeout(incrementCreditBalance, 5000); } incrementCreditBalance();


index.ts ukan phuqhat qillqatapax akan jikxatasi .

Heroku ukar uñt’ayaña

Servicio wakicht’ata, jiwasatakix servicio ukar uñstayañ pachaw purini ukhamat ukampi chikt’atäñasataki. Kunjamakitix Herokux qhipa kutix wali sum irnaqawayi (ukat nayatakix apnaqañax jasakiwa), uka jak’achasiwimp chikachasiñäni.


Qalltañatakix aka Heroku CLI kamachinak apnaqañaw wakisïna:


 $ heroku login $ heroku create jvc-graphql-server-sub Creating ⬢ jvc-graphql-server-sub... done https://jvc-graphql-server-sub-1ec2e6406a82.herokuapp.com/ | https://git.heroku.com/jvc-graphql-server-sub.git


Ukhamaraki kamachix Heroku ukan apnaqat imañ utarux mä remote ukham automáticamente yapxataraki:


 $ git remote heroku origin


Kunjamtix nayrïr qillqatanx sisktxa, Apollo Server ukax Apollo Explorer ukarux lurañ utanakanx jan ch’amanchatawa. Apollo Explorer ukax jiwasan munañanakasatak utjañapatakix, NODE_ENV medio ambiente variable ukax desarrollo ukar uñt’ayañaw wakisïna. Nayax ukax aka CLI kamachimpiw utt’ayawayta:


 $ heroku config:set NODE_ENV=development Setting NODE_ENV and restarting ⬢ jvc-graphql-server-sub... done, v3 NODE_ENV: development


Nayax Heroku ukar código ukar uñstayañatak wakicht’atäyätwa:


 $ git commit --allow-empty -m 'Deploy to Heroku' $ git push heroku


Heroku Dashboard ukan jank’ak uñakipañax Apollo Server ukan jan kuna jan walt’äwinakamp apnaqañ uñacht’ayi:


Configuración uksanx, Heroku app URL ukax aka servicio instancia ukatakix jikxatawayta:


https://jvc-graphql-server-sub-1ec2e6406a82.herokuapp.com/


Uñt’apxañani – aka link ukax janiw servicio ukan utjxaniti kunawsatix aka qillqatax uñt’ayaskani ukhaxa.


Jichhakamax GraphQL ukax aka URL ukaruw yapxataspa Apollo Server Studio ukar uñstayañataki. Ukax suscripciones ukanakax kunjamtix suyapkta ukhamarjam irnaqapki uk uñjañ yanapt’itu:


Pantalla ch’iqa tuqin Suscripción ukan jaysäwinakap uñjañäni.

Nivelación ukax WebSocket Skillz ukampiw lurasi

Jiwasax WebSocket ukan yanapt’awip ukhamarak Heroku ukan ch’amanchawip apnaqaraksnawa, mä phuqhach lurañataki, ukax lurat suscripción ukar tukusiñapataki.


Nayan amuyujax mä index.js qillqat lurawayta aka qillqatanakampi. Jilpachax, akax mä WebSocket cliente lurawayi ukatx mä servicio HTTP simulado ukham utt’ayawayi ukax nayax apnaqañjamawa cliente ukax apnaqaski uk chiqanchañataki:


 import { createClient } from "graphql-ws"; import { WebSocket } from "ws"; import http from "http"; // Create a dummy HTTP server to bind to Heroku's $PORT const PORT = process.env.PORT || 3000; http.createServer((req, res) => res.end('Server is running')).listen(PORT, () => { console.log(`HTTP server running on port ${PORT}`); }); const host_url = process.env.GRAPHQL_SUBSCRIPTION_HOST || 'ws://localhost:4000/graphql'; const client = createClient({ url: host_url, webSocketImpl: WebSocket }); const query = `subscription { creditUpdated { token customer_token credit_limit balance credit_score } }`; function handleCreditUpdated(data) { console.log('Received credit update:', data); } // Subscribe to the creditUpdated subscription client.subscribe( { query, }, { next: (data) => handleCreditUpdated(data.data.creditUpdated), error: (err) => console.error('Subscription error:', err), complete: () => console.log('Subscription complete'), } );


index.js ukan phuqhat qillqatapax akan jikxatasi .


Aka sapuru Node.js apnaqawix Heroku ukarux uñt’ayaraksnawa, GRAPHQL_SUBSCRIPTION_HOST ukan pacha mayjt’awip Heroku apnaqäw URL ukar nayraqat apnaqapktan ukaruw uñt’ayañasa.


Ukhamarakiw aka Procfile lurawayta, Heroku kunjams app qalltañax uk yatiyañataki:


 web: node src/index.js


Ukxarusti, mä machaq Heroku app lurawayta:


 $ heroku create jvc-websocket-example Creating ⬢ jvc-websocket-example... done https://jvc-websocket-example-62824c0b1df4.herokuapp.com/ | https://git.heroku.com/jvc-websocket-example.git


Ukatxa, nayax GRAPHQL_SUBSCRIPTION_HOST medio ambiente variable ukar uñt’ayawayta, ukax nayan apnaqat GraphQL servidor ukar uñacht’ayañataki:


 $ heroku --app jvc-websocket-example \ config:set \ GRAPHQL_SUBSCRIPTION_HOST=ws://jvc-graphql-server-sub-1ec2e6406a82.herokuapp.com/graphql


Aka pachanx, Heroku ukar jiwasan código ukar uñstayañatak wakicht’atätanwa:


 $ git commit --allow-empty -m 'Deploy to Heroku' $ git push heroku


Mä kutix WebSocket cliente ukax qalltawayxi ukhax Heroku Dashboard ukan estadop uñjaraksnawa:


Heroku Dashboard ukan registros uñakipt’asax jvc-websocket-example instance ukatakix walja machaq lurawinakaw jvc-graphql-server-sub servicio ukan balance propiedad ukar uñjaraksna. Nayan demostración ukanx juk’ampirus caso de uso ukarux katjañ atipxta, kawkhantix saldox cero ukar jisk’achatäki, mä payllaw luratäkaspas ukham uñtasita:


Terminal ukanxa, uka pachpa qillqatanakaruxa CLI kamachi heroku qillqatanakampiwa mantaraksna.


 2024-08-28T12:14:48.463846+00:00 app[web.1]: Received credit update: { 2024-08-28T12:14:48.463874+00:00 app[web.1]: token: 'credit-token-1', 2024-08-28T12:14:48.463875+00:00 app[web.1]: customer_token: 'customer-token-1', 2024-08-28T12:14:48.463875+00:00 app[web.1]: credit_limit: 10000, 2024-08-28T12:14:48.463875+00:00 app[web.1]: balance: 9950, 2024-08-28T12:14:48.463876+00:00 app[web.1]: credit_score: 750 2024-08-28T12:14:48.463876+00:00 app[web.1]: }


Janiw mä GraphQL servicio ukakikiti mä suscripción implementación ukax apnaqaski, jan ukasti jichhax mä cliente WebSocket uka machaq lurawinakat manq’aski.

Tukuyawi

Uñakipirinakajax declaración de misión personal ukar amtapxaspawa, ukax kawkir profesional IT ukanakatakis apnaqasispa sasaw amuyasta:


“Tiempomx características/funcionalidades ukanakar puriyañatakiw ch’amanchañama, ukax propiedad intelectual ukan valorap jilxatayañataki. Marcos, productos ukat servicios ukanakax taqi kunanak aprovechaña”. — J. Vester sat jilata


Aka manqhankir GraphQL suscripciones ukar ch’amanchañanxa, mä Apollo Server ukan Heroku ukan irnaqatapat machaq lurawinakatx sum manq’antapxta, yaqha servicio ukamp apnaqasa, ukax Heroku ukan apnaqatarakiwa —mä Node.js ukan uñt’ayat aplicación ukax WebSockets ukan apnaqatawa. Suscripciones ligeros ukanakamp aprovechasax, jan mayjt’ir datos ukanakatak jiskt’äwinak jan apayanipxtwa jan ukasti saldo de crédito ukan machaq uñstawinakap katuqañatakikiw suscribirïta.


Qalltäwinx mä tema ukanx mä principio de valor adicional ukar thaqhañatw arsuwayta, ukax nayrax qillqt’atawa. GraphQL suscripciones ukax mä suma uñacht’awiwa kunatix nayax amuyujan utjkitu kunatix ukax aljirinakaruw jank’ak machaq uñstawinak katuqañapatak jayti, jan jiskt’äwinak lurañax wakiskiti fuente de datos ukar uñtasita. Ukax Cliente 360 ukan yatiyawinakap apnaqirinakaruw wali kusisiyani, jupanakax yatipxañapawa kunatix jupanakax machaq uñstawinak kunjamtix luraski ukhamarjamaw jakasipxaspa.


Heroku ukax yaqha uñacht’awiwa, ukax nayan misión ukarjam phuqhaskakiwa, mä plataforma uñacht’ayasa, ukax CLI ukat Git kamachinak estándar ukanakamp jank’ak prototipo solucionanak lurañ yanapt’itu. Ukax janiw mä jasak thakhi suscripción ukan apnaqawip uñacht’ayañakikiti jan ukasti mä consumidor WebSockets apnaqañamp phuqhañataki.


Aka qillqatan código fuente ukar munassta ukhax GitLab ukan imañ utanakax uñakipt’añäni:



Nayax kunapachatix GraphQL yatiñanakax aka ch’amanchawimp sum nivelar puriwayta sasin sista ukhax jan axsarasaw jikxatastxa. Aka saräwix nayatakix machaq ukhamarak ch’amäkanwa ... ukat wali kusiskañarakïnwa!


Nayax jutïrin autenticación ukar ch’allt’añ amtasta, ukax yaqha oportunidad ukaw GraphQL ukat Apollo Server ukanakamp nivelar puriñapatak utjani sasaw suyt’askta. ¡Uñt'apxañani!


¡Chiqpachansa mä jachʼa uru!

L O A D I N G
. . . comments & more!

About Author

John Vester HackerNoon profile picture
John Vester@johnjvester
Information Technology professional with 25+ years expertise in application design and architecture.

HANG TAGS ukax mä juk’a pachanakanwa

AKA ARTÍCULO UKHAMARAKI UKHAMARAKI...