• Home
  • Site Aliases
    • www.cloud-native.info
    • oracle.cloud-native.info
    • Phil-Wilkins.uk
  • About
    • Background
    • Presenting Activities
    • Internet Profile
      • LinkedIn
    • About
  • Books & Publications
    • Logging in Action with Fluentd, Kubernetes and More
      • Logging in Action with Fluentd – Book
      • Fluentd Book Resources
      • Log Generator
    • API & API Platform
      • API Useful Resources
    • Oracle Integration
      • Book Website
      • Useful Reading Sources
    • Publication Contributions
  • Resources
    • GitHub
    • Oracle Integration Site
    • Oracle Resources
    • Mindmaps Index
    • Useful Tech Resources
    • Python Setup & related stuff
  • Music
    • Music Reading

Phil (aka MP3Monster)'s Blog

~ from Technology to Music

Phil (aka MP3Monster)'s Blog

Tag Archives: javascript

Apollo GraphQL – some pointers

16 Thursday Jun 2022

Posted by mp3monster in development, General, languages, node.js, Technology

≈ 2 Comments

Tags

API, code, development, GraphQL, javascript, node.js, Technology

I’ve designed a variety of GraphQL schemas and developed microservice backends. But not done much with configuring the Apollo implementation of a GraphQL server until recently. This may reflect the fact my understanding of JavaScript doesn’t extend into the world of Node.JS as much as I’d like (the problem with being a multi-language developer is you’re likely to find your way around many languages but never be a master of one). Anyway, the following content is about the implementation within a GraphQL server part of a solution. It may be these pointers are just for my benefit you might find them helpful as well.

Read more: Apollo GraphQL – some pointers

To make it easy to reference the code, we’ve added entries (n) into the code, where n is a number. This is not part of the code. But there to make the different lines referenceable. Where code should go but is not relevant to the point being made I’ve added ellipsis (…)

Dynamic loading and server configuration

import { ApolloServer } from 'apollo-server';
import { loadFilesSync } from '@graphql-tools/load-files';
import { resolvers } from './resolvers.js';   (1)
import ProviderInternalAPI from './ProviderInternalAPI.js'; (1)
import EventsInternalAPI from './EventsInternalAPI.js';  (1)
const server = new ApolloServer({
  debug : true,    (2)
  typeDefs: loadFilesSync('./schema.graphql'),   (3)
  resolvers,
  dataSources: () => {
    return {
      eventsInternalAPI: new EventsInternalAPI(),    (4)
      providerInternalAPI: new ProviderInternalAPI() (4)
      pro
    };
  }});

There is the potential to dynamically load the resolvers rather than importing each JavaScript file as we see on lines (1). The mechanics to do this is documented here. It would be cool if an opinionated implementation was provided. As shown by (3) we can take a independent schema file being loaded. The Apollo example approach for this didn’t seem to work for us, although both approaches make use of graphql-tools in a synchronous manner.

We can switch on debugging (2) for the GraphQL server, although the level of information published doesn’t appear to be significant. Ideally this setting is changed for production.

Defining the resolvers

The prefix for each resolver (1) must correlate to the name in the schema of the mutator or query (not the type as you would expect with Java). Often we don’t need all the parameters for the resolver. The documentation describes replacing each unused parameter with one or more underscores (i.e _, __ ). The underscore denoting the field not in use. However we can satisfy the indication of not being used, but keep the meaning of each position by using the underscore then a name (i.e. _parent, _args ) as shown in (2).

By taking the response into a variable (3) we can optionally log it. Trying to return using invocation line would result in the handler object rather than the payload itself. By taking the result into a variable we can log the content if desired and return the content.

The use of the backward quote is a node feature. It allows us to incorporate variables into a string by referencing it within ${} (4).

We need to supply the GraphQL server with instances with a layer of code that will interact with the resolvers. We can instantiate the instances in the declaration. The naming of the object is important (4) to the resolver.js (declarations).

import { useLogger } from "@graphql-yoga/node";
...
latestEvent (1): async (_parent, _args, { dataSources }, _info) (2)   => {
      if (log) { console.log("resolvers - get latest event"); }
      let responseValue = await dataSources.eventsInternalAPI.getLatestEvent(); (3)
      if (log) { console.log(`(4)  Resolver response for latest event:\n ${responseValue}`); }
      return responseValue;
    },

Resolver declarations

 Query: {  ...
 },
  
Mutation: {...
},
  Event: {  (1)
    providers: (event, args, { dataSources }, info) => {
      if (log) { console.log(`going to locate ${event.sources}`) }
      let responseValue = await (2) dataSources.providerInternalAPI.getProviders(event.sources);
      return responseValue;
    }

To handle the use of resolvers within a larger resolver we need to declare the resolution outside of the Query and Mutator blocks (but inside the whole declaration block)(1). The name provided needs to match the parent entity that the query resolver contributes to.

To then provide values from the outer resolution we need to prover to the chained resolution use the naming as represented in the GraphQL schema as shown by (2). The GraphQL engine will resolve the mapping values.

Web resolver URL

  // GET
  async getProvider(code) {
    console.log("getProvider (%s) directing to %s",code,this.baseURL);
    return this.get(`provider?code=${code} (1)`);
  }

The URL parameters need to be appended to the base URL path for the parent class to use in the invocation as shown by (1). The Apollo examples showed a setter option but we didn’t see the URI being addressed properly. This approach produces the relevant requirement.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Print
  • Pocket
  • Email
  • Tumblr
  • Reddit
  • Pinterest
  • WhatsApp
  • Skype

Like this:

Like Loading...

Developer Meetup – JavaScript Frameworks and Web Components

17 Monday Feb 2020

Posted by mp3monster in Dev Meetup, development, General, Oracle, Technology

≈ Leave a comment

Tags

@GeertjanW, code, developer, enterprise, framework, javascript, JET, meetup, toolket

Last night was the latest in #OracleDeveloperMeetups in London. The evening’s focus was on JavaScript Frameworks, Toolkits and Web Components.  Whilst the event is sponsored by Oracle the focus is very much on the challenges of JavaScript Frameworks.

Thanks to the Oracle and Cap Gemini teams including @GeertjanW and @PhilConsultant for an excellent session in London on Oracle Jet @OracleJET this evening. Very insightful. #oracledevelopermeetup

— David Archbold (@archbold_david) February 17, 2020

Continue reading →

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Print
  • Pocket
  • Email
  • Tumblr
  • Reddit
  • Pinterest
  • WhatsApp
  • Skype

Like this:

Like Loading...

Push Notifications with a bit of Node.js

16 Thursday Apr 2015

Posted by mp3monster in General, NodeJS Cloud, Oracle, Technology

≈ 1 Comment

Tags

API library, HelloWorld, javascript, JDeveloper, Node, node.js, npm, Oracle, prowl, push notifications

So I have written a couple of blogs about Push Notifications with a bit of Java (see here as the post that pulls all of this together). But this time we’re going to do something similar with Node.js. This blog entry is going to position us so we can then take a simple solution and push up to the cloud – as I use Oracle a lot then we’ll be looking at the Oracle cloud as a final step.

To start we need a local instance of node.js.  Given the fact it is a small footprint we can pretty much install anywhere.  So you’ll need to download Node.JS from the official site, and install it. I’m not going to walk through the installation guidance as it is well documented elsewhere (http://blog.teamtreehouse.com/install-node-js-npm-windows for example). You do want ensure you include the NPM capability (node.js packaging & deployment tool). Make sure that Node is on your path so we can reference the binary without a lots of file paths. You also want to ensure that node.js is up and running.

Next up is to the the Prowl API library that makes interacting with prowl simple and helps illustrate the deployment framework (NPM) used by node.js. So following the link from the Prowl website or go directly here  and download the library.  If you download the zip file as I did,  you’ll find it has a folder called node-prowl-master. You need to unpack this and rename to node-prowl.  and run the command

npm install node-prowl

When I first tried to deploy the Prowl API library then I did see an error. This isn’t the API but actually the Node.js installation (atleast on my Windows platform) as you can see:

installErrorI found googling using node.js and ENOENT showed up plenty of help to solve errors. In this situation the solution was purely to create the folder. Then re-running the action without problem.

When the npm command works you’ll see something like:

npm-install

So hopefully in addition to the prerequisites described in this earlier post we should have everything ready to progress.  So I’ve continued to use JDeveloper 12c, but using the general profile and set up a web solution project.  This does create a large directory structure given we’re producing some simple Javascript. But the structure is right for a proper development effort, and lazy habits form poor practises – so lets work with it.

With the project setup, we need craft a little JavaScript.  To we’re good to go – lets just try hello world, with a tiny twist, we’ll get the hostname using a Node library with this code:

 

// our very first node program

// get info about the OS
var os = require(‘os’);

// say hello world and include the hostname
console.log(“Hello world, we’re running on ” + os.hostname());

Before we do anything else, lets be a bit clever, to allow us to run our Node script within JDeveloper.  This can be done by adding a new Tool through the Tools –> External Tools … menu. Which will display the following screen:

external-tool-setup-0

 

Asa you can see in this image I have already selected New… and walked through the configuration screens, you’ll probably want to use a configuration similar to what I have in the following steps:

external-tool-setup-1

external-tool-setup-2 external-tool-setup-3

external-tool-setup-4

With this setup in JDeveloper with the Editor focus on our JavaScript, goto the Tools menu and you’ll see your Node entry. Just click on it. We’ll then see the results in the message window, as you can see here:

Hello World in JDeveloper

Alternatively in a command window you just need to run the command from the folder with the JavaScript (or include the path):

node helloworld.js

So lets take things up a notch and send our mobile device a message.  So using the following code, we can use the prowl-api and initiate a message:

var Prowl = require(‘node-prowl’); // pull in the prowl API we deployed with NPM earlier

var prowl = new Prowl(‘your-prowl-key-here‘); //setup your API key

var now = new Date();

// ready to send the message, passing a function reference to handle the response

var message = ‘hello mobile device, the time is ‘+ now.toUTCString();
prowl.push(message, ‘NodeJS App’, prowlReplyHandler);

//function to handle the response from the prowl API lib
function prowlReplyHandler ( err, remaining )
{

if( err )
{
var errorStr = err.message;
console.log( ‘I have an error ‘ + errorStr);
}
else
{
console.log( ‘I said:’ + message+ ‘; I have ‘ + remaining + ‘ calls available’ );
}

}

Note you’ll need to replace your-prowl-key-here in the above code with you genuine API key registered with the Prowl web app. Then we can run the application, and should see:

Node JS Calling Prowl

Our mobile device will show:

prowl-node-js-mobile

 

Next steps, in the next post – run through through a cloud hosting of node.js and extend the capability to be a simple service, which will mean packaging ourselves up and other exciting things.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Print
  • Pocket
  • Email
  • Tumblr
  • Reddit
  • Pinterest
  • WhatsApp
  • Skype

Like this:

Like Loading...

Aliases

  • phil-wilkins.uk
  • cloud-native.info
  • oracle.cloud-native.info

I work for Oracle, all opinions here are my own & do not necessarily reflect the views of Oracle

Oracle Ace Director Alumni

TOGAF 9

Logging in Action

Oracle Cloud Integration Book

API Platform Book


Oracle Dev Meetup London

Categories

  • App Ideas
  • Books
    • Book Reviews
    • manning
    • Oracle Press
    • Packt
  • Enterprise architecture
  • General
    • economy
    • LinkedIn
    • Website
  • Music
    • Music Resources
    • Music Reviews
  • Photography
  • Podcasts
  • Technology
    • APIs & microservices
    • chatbots
    • Cloud
    • Cloud Native
    • Dev Meetup
    • development
      • languages
        • node.js
    • drone
    • Fluentd
    • logsimulator
    • mindmap
    • OMESA
    • Oracle
      • API Platform CS
        • tools
      • Helidon
      • ITSO & OEAF
      • Java Cloud
      • NodeJS Cloud
      • OIC – ICS
      • Oracle Cloud Native
      • OUG
    • railroad diagrams
    • TOGAF
  • xxRetired

My Other Web Content & Contributions

  • Amazon Author entry
  • API Platform
  • Dev Meetup (co-managed)
  • Fluentd Book
  • ICS Book Website
  • OMESA
  • Ora World
  • Oracle Community Directory
  • Packt Author Bio
  • Phil on Blogs.Oracle.com
  • Sessionize Profile

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2,574 other subscribers

RSS

RSS Feed RSS - Posts

RSS Feed RSS - Comments

April 2023
M T W T F S S
 12
3456789
10111213141516
17181920212223
24252627282930
« Mar    

Twitter

  • Get all the details about the new enhancements to @Oracle Container Engine for Kubernetes, including Serverless… twitter.com/i/web/status/1…Next Tweet: 3 days ago
  • RT @TechWeekRO: With over 25 years of experience in the software industry, Phil Wilkins, Cloud Developer Evangelist at @Oracle, is coming t…Next Tweet: 3 days ago
  • SSH Key File Permissions blog.mp3monster.org/2023/03/28/ssh…Next Tweet: 4 days ago
  • Oracle's Assurance Service gives customers the proactive guidance they need to move their organization forward whil… twitter.com/i/web/status/1…Next Tweet: 4 days ago
  • Fraud affects many businesses and can be costly. But there’s a way to fight it. Scalable Machine Learning algorithm… twitter.com/i/web/status/1…Next Tweet: 4 days ago
Follow @mp3monster

History

Speaker Recognition

Open Source Summit Speaker

Flickr Pics

Pembroke CastleSeven Bridge Crossing
More Photos

    Social

    • View @mp3monster’s profile on Twitter
    • View philwilkins’s profile on LinkedIn
    • View mp3monster’s profile on GitHub
    • View mp3monster’s profile on Flickr
    • View philmp3monster’s profile on Twitch
    Follow Phil (aka MP3Monster)'s Blog on WordPress.com

    Blog at WordPress.com.

    • Follow Following
      • Phil (aka MP3Monster)'s Blog
      • Join 218 other followers
      • Already have a WordPress.com account? Log in now.
      • Phil (aka MP3Monster)'s Blog
      • Customize
      • Follow Following
      • Sign up
      • Log in
      • Report this content
      • View site in Reader
      • Manage subscriptions
      • Collapse this bar
     

    Loading Comments...
     

    You must be logged in to post a comment.

      Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
      To find out more, including how to control cookies, see here: Our Cookie Policy
      %d bloggers like this: