Browse Source

fix(admin-ui): Create Apollo Link to omit __typename field

This causes errors when attempting to mutate an object since the server-side schema is not expecting it.
Michael Bromley 7 years ago
parent
commit
2a7dac30e4

+ 2 - 1
admin-ui/src/app/data/data.module.ts

@@ -10,6 +10,7 @@ import { environment } from '../../environments/environment';
 import { API_URL } from '../app.config';
 import { API_URL } from '../app.config';
 import { clientDefaults } from './client-state/client-defaults';
 import { clientDefaults } from './client-state/client-defaults';
 import { clientResolvers } from './client-state/client-resolvers';
 import { clientResolvers } from './client-state/client-resolvers';
+import { OmitTypenameLink } from './omit-typename-link';
 import { BaseDataService } from './providers/base-data.service';
 import { BaseDataService } from './providers/base-data.service';
 import { DataService } from './providers/data.service';
 import { DataService } from './providers/data.service';
 import { DefaultInterceptor } from './providers/interceptor';
 import { DefaultInterceptor } from './providers/interceptor';
@@ -29,7 +30,7 @@ const stateLink = withClientState({
 
 
 export function createApollo(httpLink: HttpLink) {
 export function createApollo(httpLink: HttpLink) {
     return {
     return {
-        link:  ApolloLink.from([stateLink, httpLink.create({ uri: `${API_URL}/${API_PATH}` })]),
+        link:  ApolloLink.from([stateLink, new OmitTypenameLink(), httpLink.create({ uri: `${API_URL}/${API_PATH}` })]),
         cache: apolloCache,
         cache: apolloCache,
     };
     };
 }
 }

+ 24 - 0
admin-ui/src/app/data/omit-typename-link.ts

@@ -0,0 +1,24 @@
+import { ApolloLink } from 'apollo-link';
+
+/**
+ * The "__typename" property added by Apollo Client causes errors when posting the entity
+ * back in a mutation. Therefore this link will remove all such keys before the object
+ * reaches the API layer.
+ *
+ * See: https://github.com/apollographql/apollo-client/issues/1913#issuecomment-393721604
+ */
+export class OmitTypenameLink extends ApolloLink {
+    constructor() {
+        super((operation, forward) => {
+            if (operation.variables) {
+                operation.variables = JSON.parse(JSON.stringify(operation.variables), this.omitTypename);
+            }
+
+            return forward ? forward(operation) : null;
+        });
+    }
+
+    private omitTypename(key: string, value: string): string | undefined {
+      return key === '__typename' ? undefined : value;
+    }
+}