Apollo Federation with local schemas

Problem:

We have an eco system of 12+ micro services using either .net or node and each exposing a restful API.

I built my first Apollo GraphQL solution in early 2019 and it works really well, the down side its huge and a pain to maintain as it basically is a collection of types, resolvers and requests to the different services. So we went with federation of the different services.

Now before I begin there is an excellent article here about using local schemas with Apollo Federation and Gateway.

This works but we needed a different approach that allowed us to slowly increment changes and separate out services. We also had the issue that a couple of the services could not be touched (this was a commercial decision).

Solution:

import { ApolloServer } from 'apollo-server-express';
import { ApolloGateway, RemoteGraphQLDataSource, LocalGraphQLDataSource } from '@apollo/gateway';
import { buildFederatedSchema } from '@apollo/federation';
import { DocumentNode } from 'graphql';
import depthLimit from 'graphql-depth-limit';
import userService from './services/user';
import organisationService from './services/organisation';

const remoteServices = {
  Goals: {
    url: 'https://api.mysite.com/goal/graphql',
  },
  Curriculum: {
    url: 'https://api-mysite.com/curriculum/graphql',
  },
};

const localServices = {
  ...userService,
  ...organisationService,
};

const services = ({
  ...localServices,
  ...remoteServices,
} as unknown) as {
  [index: string]: {
    url?: string;
    schema: DocumentNode;
  };
};

const DUMMY_SERVICE_URL = 'localService';

const TOKEN = process.env.KEY || ''; // This string is uses to access the remote services inside or micro service environment. It is used once when the service starts. All other queries and requests us the bearer token supplied by the client
 
    const gateway = new ApolloGateway({
  serviceList: Object.keys(services).map((name) => ({
    name,
    url: services[name].url || DUMMY_SERVICE_URL,
  })),
  __exposeQueryPlanExperimental: false,
  buildService({ name, url }) {
    if (url === DUMMY_SERVICE_URL) {
      return new LocalGraphQLDataSource(buildFederatedSchema(services[name].schema)); // The collection of local services
    } else {
      return new RemoteGraphQLDataSource({
        url,
        willSendRequest({ request, context }) {
          request.http?.headers.set('authorization', context.token || TOKEN); // This is the clients bearer token
        },
      });
    }
  },
});

// Just a regular Apollo Server. Its exported and used in the server/app file
export const gqlServer = new ApolloServer({
  gateway,
  subscriptions: false,
  validationRules: [depthLimit(8)],
  engine: false,
  context: ({ req }) => {
    const authorization = req.headers.authorization || '';
    return { authorization };
  },
  plugins: [
    {
      serverWillStart() {
        console.log('Server starting up!');
      },
    },
  ],
});

What the above allows us to do is create local schemas like this. You can always separate this into different files.

import { gql } from 'apollo-server-express';
import ConfigManager from '../../../lib/configSource/ConfigManager';
import axios from 'axios';
import { IAuthContext, makeHeaders, Error401, NotFound, errorHandling200 } from './utils'; // Common interfaces, a method to create a request header
import errors from '../../../lib/errors';

const BASE_URL = process.env.userProfileAPI;

interface User {
  id: string;
  firstName: string;
  lastName: string;
  displayName: string;
  lastLoggedIn: string;
  roles: string[];
  organizationId: string;
}

const typeDefs = gql`
  type User @key(fields: "id") {
    id: ID!
    email: String
    firstName: String
    lastName: String
    displayName: String
    lastLoggedIn: String
    roles: [String]
    organizationId: String
    organisation: Organisation
  }

  type NotFound {
    message: String
  }

  type Error401 {
    message: String
  }

  union UserResult = User | NotFound | Error401

  extend type Organisation @key(fields: "id") {
    id: ID! @external
    users: [UserResult]
  }

  extend type Query {
    User(id: ID!): UserResult
  }
`;

const resolvers = {
  Query: {
    User: async (
      parent: unknown,
      { id }: { id: string },
      ctx: IAuthContext,
    ): Promise<null | User | NotFound | Error401> => {
      try {
        const { data } = await getUser(id, ctx);
        return {
          __typename: 'User',
          ...data,
        };
      } catch (error) {
        return errorHandling200(error, error.response.status, `User with id "${id}" not found`);
      }
    },
  },
  User: {
    async __resolveReference(user: { id: string }, ctx: IAuthContext): Promise<User | NotFound | Error401> {
      try {
        const { data } = await getUser(user.id, ctx);
        return {
          __typename: 'User',
          ...data,
        };
      } catch (error) {
        return errorHandling200(error, error.response.status, `User with id "${user.id}" not found`);
      }
    },
    async organisation({ organizationId }: { organizationId: string }): Promise<unknown | null> {
      return { __typename: 'Organisation', id: organizationId };
    },
  },
  Organisation: {
    async users(parent: { id: string }, _: unknown, ctx: IAuthContext): Promise<User[] | NotFound | Error401> {
      try {
        const users = await getUserByOrganisation(parent.id, ctx);
        return users.map(user => ({
          __typename: "User",
          ...user
        }));
      } catch (error) {
        return errorHandling200(error, error.response.status, `User with id "${parent.id}" not found`);
      }
    },
  },
};

export default {
  user: {
    schema: {
      typeDefs,
      resolvers,
    },
  },
};

Quick1: JS funky date requirement

The problem is:

Take a date object, set the time to 09:15 the following day. If that day is a Saturday, Sunday or Monday bump the date to the next Tuesday.

Solution:

const reminderTime = (date: Date): Date => {
  const response = new Date(date);
  
  const SUNDAY = 0;
  const MONDAY = 1;
  const TUESDAY = 2;
  const SATURDAY = 6;
  
  response.setDate(response.getDate() + 1);
  
  if ([SUNDAY, MONDAY, SATURDAY].some((x) => x === response.getDay())) {
    response.setDate(response.getDate() + ((TUESDAY + 7 - response.getDay()) % 7));
  }

  response.setHours(9);
  response.setMinutes(15);

  return response;
};

Is the date local or UTC? That depends on how the Date object passed into the method was created. In either case local or UTC is preserved.

Here are some proofs:

console.log(reminderTime(new Date(2020, 10, 2))); 
// Returns Tue Nov 03 2020 09:15:00 GMT+0000 (Greenwich Mean Time) 

console.log(reminderTime(new Date(2020, 10, 3)));
// Returns Wed Nov 04 2020 09:15:00 GMT+0000 (Greenwich Mean Time)

console.log(reminderTime(new Date(2020, 10, 4))); 
// Returns Thu Nov 05 2020 09:15:00 GMT+0000 (Greenwich Mean Time) 

console.log(reminderTime(new Date(2020, 10, 5)));
// Returns Fri Nov 06 2020 09:15:00 GMT+0000 (Greenwich Mean Time) 

console.log(reminderTime(new Date(2020, 10, 6)));
// Returns Tue Nov 10 2020 09:15:00 GMT+0000 (Greenwich Mean Time) 

console.log(reminderTime(new Date(2020, 10, 7)));
// Returns Tue Nov 10 2020 09:15:00 GMT+0000 (Greenwich Mean Time) 

console.log(reminderTime(new Date(2020, 10, 8)));
// Returns Tue Nov 10 2020 09:15:00 GMT+0000 (Greenwich Mean Time) 

console.log(reminderTime(new Date(2020, 10, 9)));
// Returns Tue Nov 10 2020 09:15:00 GMT+0000 (Greenwich Mean Time) 

console.log(reminderTime(new Date(2020, 11, 31)));
// Returns Fri Jan 01 2021 09:15:00 GMT+0000 (Greenwich Mean Time) 

console.log(reminderTime(new Date(2020, 1, 29)));
// Returns Tue Mar 03 2020 09:15:00 GMT+0000 (Greenwich Mean Time) 

console.log(reminderTime(new Date(2020, 1, 30)));
// Returns Tue Mar 03 2020 09:15:00 GMT+0000 (Greenwich Mean Time) 

JS Dates

Dates in JS are difficult and it is easy to reach for an external library like Moment.

But is that true? No, but there are a few gotchas.

There are two “times” we need to concern ourselves with, these are.

  • Local Time and Coordinated Universal Time (UTC). Local time refers to the time zone your computer is operating on.
  • UTC is kinda like Greenwich Mean Time and from what dates and times relate to.

Unless you are doing something really funky the date object uses local time unless you explicitly request UTC. HOWEVER, there is one exception to this. That is creating a date with a string.

Create a date with a string

new Date("2020-11-04")

This is method uses a string to set the date. Pretty straight forward but creating a date with no time is a UTC date/time.

The problem is if your computer is operating in a time zone ahead or behind UTC the date could be out by a day.

SOLUTION 1: Always include hours and minutes as a minimum.

SOLUTION 2: Do not create date objects with strings, use a different method.

Create a date with arguments

new Date(2020, 7, 19, 8, 33)

Creating a date object by using arguments. The above has a value of :

Wed, 19 Aug 2020 08:33 // Local time!

If you look closely it is not really intuitive. August is the 8th month but is represented by the number 7. That is because in Javascript is zero indexed and January is 0 …. December is 11. Not much you can do about it so do not stress and just get on with it. Treat it as a feature, and you wont end up with a UTC time when you wanted a local time.

If you are wondering how to create a UTC date with arguments:

new Date(Date.UTC(2020, 11, 10)); // 10th November 2020 <whatever time it is now>

Create a date without arguments or string

new Date()

Will create a date object with the current local date and time.

Create a date with a timestamp

new Date(1604762586100); // Sat Nov 07 2020 15:23:06 GMT+0000

You can also create a date object using a timestamp. In JavaScript, a timestamp is the amount of milliseconds elapsed since 1 January 1970. I do not remember ever using this method.

Your can get the current timestamp with:

Date.now();

That should be pretty straight forward. The key takeaways are:

  • Know that you are creating a local or UTC date object
  • Maybe avoid creating a date object with a string
  • Remember that months start at 0. January = 0 , December = 11

Quick1: JS Order array of Date objects

Solution: (Typescript)

(range as Date[]).sort((a, b) => a.valueOf() - b.valueOf());

My first thought was why not just:

(range as Date[]).sort()

But that does not work. Have a look at the MDN documents and you will see the comparison is done with character’s Unicode code.

Try this in your browsers console to see the solution working

const range = [
  new Date("2020-09-10"),
  new Date("2020-12-20"),
  new Date("2020-11-12"),
];

range.sort((a, b) => a.valueOf() - b.valueOf())

Quick1: JS array of dates

I always disliked dates in JS, but as time goes by confidence grows. It does not help that I avoid reaching for external packages unless it is really necessary.

Today I needed to generate arrays of numbers that represent days between two dates.

// Outcome needed. Inputs 2020-10-28 and 2020-11-06
const labels = [28,29,30,13,1,2,3,4,5,6];

// Solution
export const getDatesBetweenDates = (
  startDate: string,
  endDate: string
): number[] => {
  const dates: number[] = [];
  const start = new Date(startDate);
  const end = new Date(endDate);
  while (start <= end) {
    dates.push(start.getDate());
    start.setDate(start.getDate() + 1);
  }
  return dates;
};

I have no idea why I thought that would be hard

Quick1: JS, Remove duplicates from an array

There are many ways to do this by looping over the array, then using something like .some() or .findIndex().

How about this as an elegant and simple solution?

[...new Map(users.map((item) => [item.id, item])).values()]

The use case is a collection of aggregated data that could have multiple copies of a user. I needed to remove duplicates:

const users = [
  {id: "1234", name: "kirk"},
  {id: "6789", name: "spock"},
  {id: "1234", name: "kirk"},
  {id: "1234", name: "kirk"},
  {id: "rtyu", name: "bones"},
]

console.log([...new Map(users.map((item) => [item.id, item])).values()])

Copy and paste the code below into your browser console pane to see it work


const users = [
  {id: "1234", name: "kirk"},
  {id: "6789", name: "spock"},
  {id: "1234", name: "kirk"},
  {id: "1234", name: "kirk"},
  {id: "rtyu", name: "bones"},
]

[...new Map(users.map((item) => [item.id, item])).values()]

Node.js, Express.js with Typescript dream boilerplate project

I have been using Node.js with Express.js for just over a year now and Typescript for 8 months building and maintaining micro services for an SME business operating globally.

The project is at: https://github.com/daveKoala/typescript-api-starter.git

Of the 1/2 dozen I’ve created from scratch each has grown in sophistication. I now know what I want for each REST api service (in no real order):

  • Node.js with Express.js
  • Multiple environments
  • Typescript
  • Unit testing (with tests alongside the code and not in ./tests/ directory)
  • External cache
  • A ‘developer’ mode that restarts when saving
  • Debugging so I don’t have to rely on console.log
  • All end points versioned and documented
  • Authentication and Authorisation middleware
  • Custom errors
  • Re-try connections if they initially fail
  • Project auto saves and lints
  • A CI/CD pipeline that runs test and checks for external package vulnerabilities.

I am nearly there…

Node.js, Express.js and Typescript. Not much to say about this that has not already been said.

Multiple Environments: This is a bit trickier as conventional wisdom is that env values are not stored within the repo. This makes perfect sense, however the projects I am working with have 3 people at most and keeping the env within the private repo lets us quickly create new services and keep all settings, pipelines etc together with minimal fuss. It was a decision we made as a group 18 months ago and has paid off. I know there will be eye rolling at this tho’.

Unit Testing: I using Mocha.js and Chai.js no real reason apart from it works for me. There are 2 specific requirements. The first being that test scripts sit alongside the code being tested and the second is the option to publish test results. This project does both.

External Cache: Middleware on routes that intercepts the request, hashes the url and body to make an ID then queries the cache. A null response passes the request to the controller and caches the results.

‘Developer mode’: Easy with Nodemon and scripts within the package.json file. There are a few other useful scripts including a “lazy script” that runs tests, linting, audits and a build process.

Debugging: I’ll leave that to Visual Studio Code and commit any settings files.

All end points versioned and documented: Using Swagger and OpenDoc to create nice api docs. Added advantage is that you can link/download to the OpenDocs JSON into Postman to create collections.

Versioning: I opted for the “version via the request header” approach. Why? I like that the urls don’t change and because it is strict. Strict as in, if you fail to request a version you get feedback telling you what you need to do. The main thing about versioning is declaring a contract and sticking to it.

Authentication and Authorisation: Separate middleware that can leverage different methods specified by the project.

Custom errors: Easy enough, create meaningful error messages and responses. They also accept plugins for external logging.

Re-try connections if they initially fail: Also known as a Circuit Breaker pattern.

Project auto saves and lints: Let Visual Studio handle this and commit settings to the project.

CI/CD Pipeline: Convention over configuration and making use of files like Azure Pipelines YAML files to describe and run CI/CD processes.

This is an ongoing project and can be found at: https://github.com/daveKoala/typescript-api-starter.git

Quick1: JS + Vue.js pause before

Problem:

I had a large list that a user could reorder by dragging and dropping. All work beautifully.

Except persisting the changes to the database. I did not want the an API call for every drop action or a button that the user clicked that said, “Save list”.

Solution:

Its a Vue.js project and the drag and drop had two events called “start” and “end”. These would call the corresponding methods below.

“endDrag” starts a timer that will run the supplied method in 1.5 seconds after the dragging has stopped. If the user starts “dragging” again the timer is cancelled

methods: {
    endDrag(): void {
      this.timer = setTimeout(this.distpatchOrderedList, 1500);
      this.drag = false;
    },
    startDrag(): void {
      clearTimeout(this.timer);
      this.drag = true;
    },
   distpatchOrderedList(): void {
     // Do some magic
   }
}

Quick1: Typescript

I’ve been using Typescript for 12 months and every now and then I get blocked. I used to do a fair bit of ‘typescript ignore’ in my code just to keep things moving and depend on my tests to throw up mistakes.

This I think ha caught me out a few times in different circumstances.

interface Options {
  id: string;
  name: string;
}
const options: Options = {id: "qwerty", name: "andy pandy"}

Object(options).forEach(key => {
  localOptions[key] = options[key]
});

The above would not compile and give the following message (note if I set the line to be ignored the code still worked)

Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘xxxx’. No index signature with a parameter of type ‘string’ was found on type ‘xxxx’

So how to comply with Typescript?

I found two options. One went about extending the object constructor and adding overloads the second is type-casting. Extending the object constructor is probably more “correct” but type-casting worked and when you read the code it simpler to understand (IMHO)

interface Options {
  id: string;
  name: string;
}
const options: Options = {id: "qwerty", name: "andy pandy"}

Object(options).forEach(key => {
  localOptions[key as keyof Options] = options[key as keyof Options]
});

Does it work and does it address the issue? Yes it does.

Javascript simple date string comparison

I need to check if a date string is within a date range.

// Set up
const dateRange = ["2020-07-30", "2020-07-20"];

let n = 0;

const collection = [
{ "createdOn": "2020-07-01", title: `title # ${ n++ }` },
{ "createdOn": "2020-07-10", title: `title # ${ n++ }` },
{ "createdOn": "2020-07-20", title: `title # ${ n++ }` }, // Include
{ "createdOn": "2020-07-21", title: `title # ${ n++ }` }, // Include
{ "createdOn": "2020-07-21", title: `title # ${ n++ }` }, // Include
{ "createdOn": "2020-07-30", title: `title # ${ n++ }` }, // Include
{ "createdOn": "2020-07-30", title: `title # ${ n++ }` }, // Include
{ "createdOn": "2020-07-31", title: `title # ${ n++ }` },
];

// Solution
const filter = (collection, dateRange) => {
    const dates = [...dateRange].sort(); // Sorts the date range: from -> to
    return collection.filter(item => item.createdOn >= dates[0] && item.createdOn <= dates[1]); // returns either array of objects or an empty array
}

console.table(filter(collection, dateRange));

┌─────────┬──────────────┬─────────────┐ 
│ (index) │ createdOn    │ title       │ 
├─────────┼──────────────┼─────────────┤ 
│ 0       │ '2020-07-20' │ 'title # 2' │ 
│ 1       │ '2020-07-21' │ 'title # 3' │ 
│ 2       │ '2020-07-21' │ 'title # 4' │ 
│ 3       │ '2020-07-30' │ 'title # 5' │ 
│ 4       │ '2020-07-30' │ 'title # 6' │ 
└─────────┴──────────────┴─────────────┘