paint-brush
Go Lekantšha Mabokgoni a Ka a GraphQL: Dipeeletšo tša Nako ya Sebeleka@johnjvester
488 dipuku tša go balwa
488 dipuku tša go balwa

Go Lekantšha Mabokgoni a Ka a GraphQL: Dipeeletšo tša Nako ya Sebele

ka John Vester10m2024/09/18
Read on Terminal Reader

Nako e telele kudu; Go bala

Thuma go se nene go tsenelela go hlahloba dipeeletšo tša datha tša nako ya nnete ka go šomiša GraphQL go amogela ka go iketla diapdeite tša lehlakoreng la seva ka thušo go tšwa go moreki wa WebSocket.
featured image - Go Lekantšha Mabokgoni a Ka a GraphQL: Dipeeletšo tša Nako ya Sebele
John Vester HackerNoon profile picture

Ka mengwaga ye mmalwa bjale, ke lekile go šupa ditlhako, ditšweletšwa, le ditirelo tšeo di dumelelago ditsebi tša theknolotši go boloka tsepamiso ya tšona ya go tsepelela go katološeng boleng bja thoto ya bona ya bohlale. Ye e tšwela pele go ba leeto le le makatšago go nna, leo le tletšego ka dibaka tša moswananoši tša go ithuta.


Moentšeneare yo a lego ka go nna o sa tšwa go ipotšiša ge e ba go be go e-na le boemo bjoo go bjona nka hwetšago mohola wa bobedi bakeng sa kgopolo yeo e lego gona yeo ke boletšego ka yona pele. Ka mantšu a mangwe, na nka kgona go šupa mohola o mongwe wo o nago le tekanyo e swanago ya khuetšo le tharollo ya mathomo ya motswadi yeo e lemogilwego peleng?


Bakeng sa sehlogo se, ke be ke nyaka go itahlela ka gare ga GraphQL go bona seo nka se hwetšago.


Sehlogong sa ka sa “ Ge e le Nako ya go Fa REST Khutšo ”, ke boletše ka kamoo go nago le maemo a kgonthe a lefase ge GraphQL e kgethwa go feta tirelo ya RESTful. Re ile ra sepela ka mokgwa wa go aga le go tsenya tirišong API ya GraphQL re šomiša Apollo Server.


Mo posong ye ya go latela, ke rera go level up tsebo ya ka ya GraphQL ka go sepela ka dipeeletšo bakeng sa go hwetša ya data ya nako ya kgonthe. Re tla aga gape tirelo ya WebSocket go ja dipeeletšo.

Recap: Moreki 360 Taba ya Tšhomišo

Sehlogo sa ka sa pele se be se tsepame go dikologa taba ya tšhomišo ya Moreki 360, moo bathekgi ba kgwebo ya ka ya boikgopolelo ba bolokago dikgoboketšo tše di latelago tša datha:


  • Tshedimošo ya bareki
  • Tshedimošo ya aterese
  • Mekgwa ya go ikgokaganya
  • Dika tša mokitlana


Phenyo e kgolo ka go diriša GraphQL ke gore kgopelo e tee ya GraphQL e ka hwetša ya data ka moka ye e nyakegago bakeng sa leswao la moreki (boitšhupo bja moswananoši).


 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 }


Go šomiša mokgwa wa RESTful go hwetša pono e tee (360) ya moreki go be go tla nyaka gore dikgopelo tše ntši le dikarabo di rokelelwe mmogo. GraphQL e re fa tharollo yeo e šomago gabotse kudu.

Level Up Dipakane

E le gore motho a kgone go ba maemong a godimo karolong le ge e le efe ya bophelo, o swanetše go fihlelela dipakane tše difsa. Bakeng sa dipakane tša-ka ka noši mo, se se bolela gore:


  • Go kwešiša le go phethagatša tšhišinyo ya boleng bja peeletšo ka gare ga GraphQL.
  • Go šomiša phethagatšo ya WebSocket go ja peeletšo ya GraphQL.


Kgopolo ya go šomiša dipeeletšo godimo ga dipotšišo le diphetogo tša leabela ka gare ga GraphQL ke mokgwa wo o kgethilwego ge maemo a a latelago a fihlelelwa:


  • Diphetogo tše nnyane, tše di oketšegago go dilo tše kgolo
  • Diapdeite tša go khutša tša fase, tša nako ya nnete (go swana le tirišo ya poledišano) .


Se se bohlokwa ka ge go phethagatša dipeeletšo ka gare ga GraphQL e se selo se se sa rego selo. Ga se feela gore seva ya motheo e tla swanelwa ke go mpshafatšwa, eupša tirišo yeo e jago e tla nyaka go hlangwa lefsa mo gongwe gape.


Ka mahlatse, molato wa tšhomišo wo re o phegelelago ka mohlala wa rena wa Moreki 360 ke wo o swanetšego kudu bakeng sa dipeeletšo. Gape, re tla be re phethagatša mokgwa wa WebSocket wa go diriša dipeeletšo tšeo.


Go swana le pele, ke tla tšwela pele go šomiša Apollo go ya pele.

Leveling Up Ka Dipeeletšo Creds

Sa pele, re swanetše go tsenya makgobapuku a nyakegago go thekga dipeeletšo ka seva ya ka ya Apollo GraphQL:


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


Ka dilo tšeo di hlomilwe, ke ile ka lebiša tlhokomelo go mpshafatšeng index.ts go tšwa polokelong ya ka ya mathomo go katološa typedefs constant ka tše di latelago:


 type Subscription { creditUpdated: Credit }


Ke ile ka hloma gape le selo se se sa fetogego sa go bea mohlala o mofsa PubSub gomme ka hlola peeletšo ya mohlala yeo re tlago go e šomiša ka morago:


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


Ke hlwekišitše di-resolver tše di lego gona gomme ka oketša Subscription ye mpsha ya molato wo o mofsa wa tšhomišo:


 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']), } } };


Ke moka ke ile ka refactored peakanyo ya seva gomme ka tsebagatša tlhamo ya peeletšo:


 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`); });


Go ekiša diapdeite tšeo di laolwago ke bareki, ke ile ka hlama mokgwa wo o latelago go oketša tekatekano ya mokitlana ka $50 metsotswana e mengwe le e mengwe e mehlano ge tirelo e dutše e šoma. Gatee-tee ge tšhelete yeo e šetšego e fihla (goba e feta) tekanyo ya mokitlana ya R10 000, ke bušetša tšhelete yeo e šetšego morago go R1 000, ke ekiša tefo ya tšhelete yeo e šetšego yeo e dirwago.


 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();


Faele ya index.ts ka botlalo e ka hwetšwa mo .

Deploy go Heroku

Ka tirelo e loketše, ke nako ya gore re tsenye tirelo yeo gore re kgone go dirišana le yona. Ka ge Heroku e šomile gabotse kudu la mafelelo (gomme go bonolo gore ke e šomiše), a re kgomareleng mokgwa woo.


Go thoma, ke be ke swanetše go sepetša ditaelo tše di latelago tša Heroku CLI:


 $ 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


Taelo e ile ya tlaleletša gape ka go iketla polokelo yeo e šomišwago ke Heroku bjalo ka remoutu:


 $ git remote heroku origin


Go swana le ge ke lemogile sehlogong sa ka sa pele, Apollo Server e šitiša Apollo Explorer tikologong ya tšweletšo. Go boloka Apollo Explorer e hwetšagala bakeng sa dinyakwa tša rena, ke be ke swanetše go beakanya phetogo ya tikologo NODE_ENV go tlhabollo. Ke beile seo ka taelo ye e latelago ya CLI:


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


Ke be ke ikemišeditše go tsenya khoutu ya ka go Heroku:


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


Pono ya ka pela ya Heroku Dashboard e bontšhitše Apollo Server ya ka e šoma ntle le ditaba le ge e le dife:


Karolong ya Dipeakanyo, ke hweditše URL ya tirišo ya Heroku bakeng sa mohlala wo wa tirelo:


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


Hle ela hloko – kgokagano ye e ka se sa ba tirelong ka nako yeo sengwalwa se se phatlalatšwago.


Ga bjale, nka tlaleletša GraphQL go URL ye go thoma Apollo Server Studio. Se se ntumeletše go bona dipeeletšo di šoma bjalo ka ge go be go letetšwe:


Hlokomela dikarabo tša Peeletšo ka lehlakoreng le letona la skrine.

Go Lekalekantšha Ka WebSocket Skillz

Re ka diriša thekgo ya WebSocket le bokgoni bja Heroku go hlama phethagatšo yeo e jago peeletšo yeo re e hlotšego.


Tabeng ya ka, ke hlotše faele ya index.js yeo e nago le dikagare tše di latelago. Ge e le gabotse, se se hlotše moreki wa WebSocket gomme gape sa hloma tirelo ya HTTP ya bofora yeo nka e šomišago go netefatša gore moreki o be a šoma:


 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'), } );


Faele ya index.js ka botlalo e ka hwetšwa mo .


Re ka tsenya tirišong ye bonolo ya Node.js go Heroku le yona, re kgonthiša gore re beakanya phetogo ya tikologo GRAPHQL_SUBSCRIPTION_HOST go URL ya tirišo ya Heroku yeo re e šomišitšego pejana.


Ke ile ka bopa gape Procfile ye e latelago go botša Heroku kamoo a ka thomago tirišo ya ka:


 web: node src/index.js


Se se latelago, ke ile ka hlama tirišo e mpsha ya Heroku:


 $ 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


Ka morago ga moo, ke beakanya phetogo ya tikologo ya GRAPHQL_SUBSCRIPTION_HOST go šupa go seva ya ka ya GraphQL yeo e šomago:


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


Mo nakong ye, re ikemišeditše go tsenya khoutu ya rena go Heroku:


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


Ge moreki wa WebSocket a thomile, re ka bona maemo a gagwe ka go Heroku Dashboard:


Ka go lebelela dilog ka gare ga Heroku Dashboard bakeng sa mohlala wa jvc-websocket-example , re ka bona diapdeite tše ntši go thepa ya balance ya tirelo ya jvc-graphql-server-sub . Ka demo ya ka, ke ile ka ba ka kgona go swara taba ya tšhomišo moo tekatekano e ilego ya fokotšwa go fihla go lefela, ke ekiša gore tefo e dirilwe:


Ka terminal, re ka fihlelela dilog tšeo di swanago ka dilog tša heroku tša taelo ya CLI.


 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]: }


Ga se fela gore re na le tirelo ya GraphQL yeo e nago le phethagatšo ya peeletšo ye e šomago, eupša bjale re na le moreki wa WebSocket yo a jago diapdeite tšeo.

Mafetšo

Babadi ba ka ba ka gopola polelo ya ka ya thomo ya motho ka noši, yeo ke bonago e ka šoma go setsebi sefe goba sefe sa IT:


“Tsepamiša nako ya gago go tlišeng dibopego/mošomo wo o katološago boleng bja thoto ya gago ya bohlale. Leverage ditlhako, ditšweletšwa le ditirelo bakeng sa se sengwe le se sengwe.” — J. V e s t e r


Ka go itahlela mo go tseneletšego ka gare ga dipeeletšo tša GraphQL, re jele ka katlego diapdeite go tšwa go Sefepedi sa Apollo seo se šomago go Heroku ka go šomiša tirelo ye nngwe yeo gape e šomago go Heroku—tirišo ye e theilwego go Node.js yeo e šomišago WebSockets. Ka go diriša dipeeletšo tše boima, re ile ra efoga go romela dipotšišo tša datha yeo e sa fetogego eupša ra fo ingwadišetša go amogela diapdeite tša tekatekano ya mokitlana ge di direga.


Matseno, ke boletše go nyaka molao wa motheo wa boleng bja tlaleletšo ka gare ga hlogotaba yeo ke ngwadilego ka yona pele. Dipeeletšo tša GraphQL ke mohlala o mobotse kudu wa seo ke bego ke se naganne ka gobane e dumelela bareki go amogela diapdeite ka pela, ntle le go hloka go dira dipotšišo kgahlanong le ya data ya mohlodi. Se se tla dira gore bareki ba datha ya Moreki 360 ba thabe kudu, ba tseba gore ba ka phela diapdeite ge di direga.


Heroku ke mohlala o mongwe wo o tšwelago pele go kgomarela polelo ya ka ya thomo ka go fana ka sefala seo se nkgontšhago go dira ditharollo tša prototype ka pela ka go šomiša CLI le ditaelo tša Git tša maemo. Se ga se mphe fela tsela ye bonolo ya go bontšha taba ya tšhomišo ya peeletšo ya ka eupša go phethagatša moreki yo a šomišago WebSockets le yena.


Ge e ba o na le kgahlego go khoutu ya mohlodi ya sehlogo se, hlahloba mafelo a ka a polokelo go GitLab:



Ke ikwa ke itshepa ge ke bolela gore ke atlegile go lekalekantšha bokgoni bja ka bja GraphQL ka maiteko a. Leeto le e be e le le lefsa ebile e le tlhohlo go nna ... gomme gape le le monate kudu!


Ke rera go itahlela ka gare ga netefatšo ye e latelago, yeo ka kholofelo e fago sebaka se sengwe sa go ba maemong a godimo le GraphQL le Apollo Server. Dula o lebeletše!


Eba le letšatši le lebotse e le ka kgonthe!

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 YA GO FEGA

ARTICLE YE E HLAHILWE KA...