aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.42k stars 2.12k forks source link

No pubsub module applied for subscription #2184

Closed EgidioCaprino closed 5 years ago

EgidioCaprino commented 5 years ago

Which Category is your question related to?

PubSub among with API.

What AWS Services are you utilizing? API with Cognito.

Provide additional details e.g. code snippets I'm doing the configuration in this way:

Amplify.configure({
  Auth: {
    identityPoolId,
    region,
    userPoolId,
    userPoolWebClientId,
  },
  API: {
    graphql_endpoint: graphqlEndpoint,
    aws_appsync_region: region,
    aws_appsync_authenticationType: 'AMAZON_COGNITO_USER_POOLS',
    graphql_headers: graphqlHeaders,
  },
});

and I'm calling

const query = (
  `${userFragment}
  ${messageFragment}
  subscription MessageCreated($conversationId: ID!) {
    messageCreated(conversationId: $conversationId) {
      ...MessageFragment
    }
  }`
);
subscribe(query, { conversationId }, callback);

But at runtime I get this error

No pubsub module applied for subscription

I can't find in the doc where it explains how to do the configuration with API.

Can you please help me?

powerful23 commented 5 years ago

@EgidioCaprino did you do something like import Pubsub from '@aws-amplify/pubsub' at the beginning. This error happens when the pubsub category is not imported into your app.

EgidioCaprino commented 5 years ago

@powerful23 I'm doing this but still get the same issue

import Amplify from '@aws-amplify/core';
import Auth from '@aws-amplify/auth';
import PubSub from '@aws-amplify/pubsub';

const graphQLHeaders = async () => {
  const { idToken } = await Auth.currentSession();
  return { Authorization: idToken.jwtToken };
};

export default (config: any) => {
  const { API = {}, ...rest } = config;
  const apiConfig = {
    ...API,
    graphql_headers: graphQLHeaders,
  };
  PubSub.configure({
    ...rest,
    API: apiConfig,
  });
  Amplify.configure({
    ...rest,
    API: apiConfig,
  });
};
EgidioCaprino commented 5 years ago

Modular imports does not seem to work when using API and PubSub together in AppSync subscriptions.

elorzafe commented 5 years ago

@EgidioCaprino I have this app code working. ( I previously installed @aws-amplify/core @aws-amplify/pubsub @aws-amplify/api)

import React, { Component } from 'react';
import Amplify from '@aws-amplify/core';
import API from '@aws-amplify/api';
import _PubSub from '@aws-amplify/pubsub';
import _Auth from '@aws-amplify/auth';
import awsconfig from './aws-exports';
import { onCreateTodo } from './graphql/subscriptions'; 
Amplify.configure({
  Auth: {
    identityPoolId: awsconfig.aws_cognito_identity_pool_id,
    region: awsconfig.aws_cognito_region,
    userPoolId: awsconfig.aws_user_pools_id,
    userPoolWebClientId: awsconfig.aws_user_pools_web_client_id,
  },
  aws_appsync_graphqlEndpoint: awsconfig.aws_appsync_graphqlEndpoint,
  aws_appsync_region: awsconfig.aws_appsync_region,
  aws_appsync_authenticationType: awsconfig.aws_appsync_authenticationType,
});

class App extends Component {

  async componentDidMount(){
    API.graphql({query: onCreateTodo}).subscribe({
      next: console.log
    })
  }

  render() {
    return (
      <div className="App">
       Test
      </div>
    );
  }
}

export default App;
camarrone commented 5 years ago

Hello all,

I'm having the same issue using API_KEY.

It's being used on a EmberJS application. This is my code:

import Service from '@ember/service';
import awsmobile from '../aws-exports';

import Amplify, { Auth, API, graphqlOperation, PubSub  } from "aws-amplify";

import * as queries from '../graphql/queries';
import * as subscriptions from '../graphql/subscriptions';

Amplify.configure(awsmobile);
API.configure(awsmobile);
PubSub.configure(awsmobile);

export default Service.extend({
    AppSync: API,

    async queryAndSub(){
        try{
            const allTodos = await API.graphql(graphqlOperation(queries.getAllPosts));
            console.log(allTodos);

            const subscription = API.graphql(
                graphqlOperation(subscriptions.addedPost)
            ).subscribe({
                next: (todoData) => console.log(todoData)
            });
        }
        catch(err){
            console.log('ERROR');
            console.log(err);
        }
    }
});

I checked the aws-amplify code and at the beginning of _graphqlSubscribe method there is the following statement (amplify-js/packages/api/src/API.ts - line 418 )

if (Amplify.PubSub && typeof Amplify.PubSub.subscribe === 'function')

In my case, typeof Amplify.PubSub.subscribe === 'function' returns true. If I console PubSub it's also returns true. I can see PubSub settings in the console.

What am I missing here?

Thanks for the help!

EgidioCaprino commented 5 years ago

It's a react-native issue, not related to Amplify. I see it's fixed on master in this commit.

powerful23 commented 5 years ago

Closing the issue. Feel free to reopen if you still have this issue.

alkurop commented 4 years ago

I'm having this issue again. I'm using next.js. When I run dev build, everything good. But on prod build my page crashes with No pubsub module applied for subscription

import Amplify, { API, PubSub } from "aws-amplify";
import config from "./src/aws-exports";

API.configure(config);
Amplify.configure(config);
PubSub.configure(config);
React.useEffect(() => {
    const sub1 = API.graphql(graphqlOperation(onCreateProduct)).subscribe(
      function(result) {
      ...
      }
    );
 return function cleanup() {
      sub1.unsubscribe();
 };
  });
minaairsupport commented 4 years ago

I have the same issue I tried all these solutions but none of them work any hint why I am still getting this issue

import Amplify from "@aws-amplify/core";
import PubSub from "@aws-amplify/pubsub";
import API from "@aws-amplify/api";
import config from "./aws-exports";

Amplify.configure(config);
PubSub.configure(config);
API.configure(config);
CiscoKidxx commented 4 years ago

Why is the total of importing Storage, API, Auth and PubSub individually greater than importing "aws-amplify" entirely?!

arantespp commented 4 years ago

This configuration works for me:

import API, { graphqlOperation } from '@aws-amplify/api';
import '@aws-amplify/pubsub';

API.configure({
  aws_appsync_graphqlEndpoint:
    'https://API.appsync-api.us-east-1.amazonaws.com/graphql',
  aws_appsync_region: 'us-east-1',
  aws_appsync_authenticationType: 'API_KEY',
  aws_appsync_apiKey: 'da2-KEY',
});
kldeb commented 4 years ago

None of these solutions are working for me including @elorzafe. Has anyone found another solution?

kldeb commented 4 years ago

Fixed my problem by:

minaairsupport commented 4 years ago

for me that's working use aws-amplify instead of @aws-amplify

import Amplify, { API } from "aws-amplify";
import PubSub from "@aws-amplify/pubsub";
import awsmobile from "./aws-exports";

Amplify.configure(awsmobile);
PubSub.configure(awsmobile);
API.configure(awsmobile);
atlowell-smpl commented 4 years ago

Same issue in Ionic Angular 4, even without attempting to call a subscription. Just having one in API.service.ts is enough to cause the entire app to shutdown with this error. I've tried all of the fixes listed above.

My code:

main.ts:

import { environment } from './environments/environment';
import Amplify from '@aws-amplify/core';
import API from '@aws-amplify/api';
import PubSub from '@aws-amplify/pubsub';

Amplify.configure(environment.awsconfig);
PubSub.configure(environment.awsconfig);
API.configure(environment.awsconfig);

...

environment.ts:

export const environment = {
  awsconfig: {
    Auth: {
      region: 'us-east-2',
      userPoolId: 'USER_POOL_ID',
      userPoolWebClientId: 'USER_POOL_CLIENT',
      mandatorySignIn: true,
      cookieStorage: {
        domain: 'localhost',
        path: '/',
        secure: false
      }
    },
    Storage: {
      AWSS3: {
        bucket: 'BUCKET_NAME',
        region: 'us-east-2'
      }
    },
    aws_appsync_graphqlEndpoint: 'ENDPOINT_URL',
    aws_appsync_region: 'us-east-2',
    aws_appsync_authenticationType: 'AMAZON_COGNITO_USER_POOLS'
  }
}

API.service.ts:

import { Injectable } from "@angular/core";
import API, { graphqlOperation } from "@aws-amplify/api";
import * as Observable from "zen-observable";

export type testSubscription = {
  __typename: "Test;
  // Id of the user this notification is for
  teststring: string;
};

@Injectable({
  providedIn: "root"
})
export class APIService {
  TestListener: Observable<
    TestSubscription
  > = API.graphql(
    graphqlOperation(
      `subscription Test($teststring: String!) {
        test(teststring: $teststring) {
          __typename
          teststring
        }
      }`
    )
  ) as Observable<TestSubscription>;
}

The API.service.ts code was auto-generated by amplify codegen.

The error (on page load):

Error: No pubsub module applied for subscription
    at APIClass.push../node_modules/@aws-amplify/api/lib-esm/API.js.APIClass._graphqlSubscribe (API.js:590)
    at APIClass.push../node_modules/@aws-amplify/api/lib-esm/API.js.APIClass.graphql (API.js:475)
    at new APIService (API.service.ts:2937)
    at core.js:16346
    at _callFactory (core.js:30486)
    at _createProviderInstance (core.js:30429)
    at resolveNgModuleDep (core.js:30388)
    at NgModuleRef_.get (core.js:31578)
    at injectInjectorOnly (core.js:734)
    at ɵɵinject (core.js:744)

package.json dependencies:

"dependencies": {
    "@angular/common": "~8.1.2",
    "@angular/core": "^8.1.3",
    "@angular/forms": "~8.1.2",
    "@angular/platform-browser": "~8.1.2",
    "@angular/platform-browser-dynamic": "~8.1.2",
    "@angular/router": "~8.1.2",
    "@aws-amplify/api": "^2.1.3",
    "@aws-amplify/pubsub": "^1.3.3",
    "@aws-amplify/storage": "^2.1.3",
    "@ionic-native/core": "^5.19.1",
    "@ionic-native/splash-screen": "^5.19.1",
    "@ionic-native/status-bar": "^5.19.1",
    "@ionic/angular": "^4.11.8",
    "aws-amplify": "^1.3.3",
    "aws-amplify-angular": "^4.1.3",
    "cordova-ios": "^5.1.1",
    "core-js": "^2.5.4",
    "fast-safe-stringify": "^2.0.7",
    "fs": "0.0.1-security",
    "moment": "^2.24.0",
    "rxjs": "~6.5.1",
    "sharp": "^0.24.0",
    "tslib": "^1.9.0",
    "validator": "^12.2.0",
    "web": "0.0.2",
    "zone.js": "~0.9.1"
}
github-actions[bot] commented 3 years ago

This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.

Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels or Discussions for those types of questions.