attachConnectorsToContext.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. Object.defineProperty(exports, "__esModule", { value: true });
  2. var graphql_1 = require("graphql");
  3. var deprecated_decorator_1 = require("deprecated-decorator");
  4. var _1 = require(".");
  5. // takes a GraphQL-JS schema and an object of connectors, then attaches
  6. // the connectors to the context by wrapping each query or mutation resolve
  7. // function with a function that attaches connectors if they don't exist.
  8. // attaches connectors only once to make sure they are singletons
  9. var attachConnectorsToContext = deprecated_decorator_1.deprecated({
  10. version: '0.7.0',
  11. url: 'https://github.com/apollostack/graphql-tools/issues/140',
  12. }, function (schema, connectors) {
  13. if (!schema || !(schema instanceof graphql_1.GraphQLSchema)) {
  14. throw new Error('schema must be an instance of GraphQLSchema. ' +
  15. 'This error could be caused by installing more than one version of GraphQL-JS');
  16. }
  17. if (typeof connectors !== 'object') {
  18. var connectorType = typeof connectors;
  19. throw new Error("Expected connectors to be of type object, got " + connectorType);
  20. }
  21. if (Object.keys(connectors).length === 0) {
  22. throw new Error('Expected connectors to not be an empty object');
  23. }
  24. if (Array.isArray(connectors)) {
  25. throw new Error('Expected connectors to be of type object, got Array');
  26. }
  27. if (schema['_apolloConnectorsAttached']) {
  28. throw new Error('Connectors already attached to context, cannot attach more than once');
  29. }
  30. schema['_apolloConnectorsAttached'] = true;
  31. var attachconnectorFn = function (root, args, ctx) {
  32. if (typeof ctx !== 'object') {
  33. // if in any way possible, we should throw an error when the attachconnectors
  34. // function is called, not when a query is executed.
  35. var contextType = typeof ctx;
  36. throw new Error("Cannot attach connector because context is not an object: " + contextType);
  37. }
  38. if (typeof ctx.connectors === 'undefined') {
  39. ctx.connectors = {};
  40. }
  41. Object.keys(connectors).forEach(function (connectorName) {
  42. var connector = connectors[connectorName];
  43. if (!!connector.prototype) {
  44. ctx.connectors[connectorName] = new connector(ctx);
  45. }
  46. else {
  47. throw new Error("Connector must be a function or an class");
  48. }
  49. });
  50. return root;
  51. };
  52. _1.addSchemaLevelResolveFunction(schema, attachconnectorFn);
  53. });
  54. exports.default = attachConnectorsToContext;
  55. //# sourceMappingURL=attachConnectorsToContext.js.map