aws-amplify#API JavaScript Examples

The following examples show how to use aws-amplify#API. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: APIHandler.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
sendDrawioPostRequest = async (query, processor) => {
  let apiName = 'PerspectiveDrawioWebRestAPI';
  let path = `/resources`;
  let myInit = {
    body: query.body,
    headers: {
      Authorization: `Bearer ${(await Auth.currentSession())
        .getIdToken()
        .getJwtToken()}`,
    },
  };

  return API.post(apiName, path, myInit)
    .then((response) => {
      return wrapResponse(processor(response, query.params), false);
    })
    .catch((error) => {
      return wrapResponse(error, true);
    });
}
Example #2
Source File: index.js    From InstagramClone with MIT License 6 votes vote down vote up
Feed = () => {

  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetchPosts();
  }, [])

  const fetchPosts = async () => {
    try {
      const postsData = await API.graphql(graphqlOperation(listPosts));
      setPosts(postsData.data.listPosts.items);
    } catch (e) {
      console.log(e.message);
    }
  }

  return (
    <FlatList
      data={posts}
      renderItem={({item}) => <Post post={item} />}
      keyExtractor={({id}) => id}
      ListHeaderComponent={Stories}
    />
  )
}
Example #3
Source File: index.js    From InstagramClone with MIT License 6 votes vote down vote up
Stories = () => {

  const [stories, setStories] = useState([]);

  useEffect(() => {
    fetchStories();
  }, []);

  const fetchStories = async () => {
    try {
      const storiesData = await API.graphql(graphqlOperation(listStorys));
      setStories(storiesData.data.listStorys.items);
    } catch (e) {
      console.log(e);
    }
  }

  return (
    <FlatList
      data={stories}
      keyExtractor={({user: {id}}) => id}
      horizontal
      showsHorizontalScrollIndicator={false}
      style={styles.container}
      renderItem={({item}) => <Story story={item}/>}
    />
  )
}
Example #4
Source File: pinpoint.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
send = event => {
  const batchItemId = uuid();
  const eventId = uuid();

  const body = {
    BatchItem: {
      [batchItemId]: {
        Events: {
          [eventId]: event
        }
      }
    }
  };

  return API.post("pinpointApi", "", { body, headers });
}
Example #5
Source File: translateAPI.js    From Amazon-Connect-Chat-Translate-Demo with MIT License 6 votes vote down vote up
async function ProcessChatTextAPI(content, sourceLang, targetLang, terminologyNames) {
    const apiName = 'amazonTranslateAPI';
    const path = '/translate';
    const myInit = { // OPTIONAL
        body: { 'content': content, 'sourceLang': sourceLang, 'targetLang': targetLang, 'terminologyNames': terminologyNames },
        headers: {}, // OPTIONAL
    };
    console.log("myInit :", myInit);

    try {
        var result = await API.post(apiName, path, myInit);
        console.log("ProcessChatTextAPI: ", result);
        return result;
    }
    catch (error) {
        console.error("ProcessChatTextAPI: ", error);
        return error;
    }
}
Example #6
Source File: APIHandler.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
sendPostRequest = async (query, processor) => {
  let apiName = 'PerspectiveWebRestAPI';
  let path = `/resources`;
  let myInit = {
    body: query.body,
    headers: {
      Authorization: `Bearer ${(await Auth.currentSession())
        .getIdToken()
        .getJwtToken()}`,
    },
  };
  return API.post(apiName, path, myInit)
    .then((response) => {
      return wrapResponse(processor(response, query.params), false);
    })
    .catch((error) => {
      return wrapResponse(error, true);
    });
}
Example #7
Source File: APIHandler.js    From aws-perspective with Apache License 2.0 6 votes vote down vote up
sendGetRequest = async (query, processor) => {
  let apiName = 'PerspectiveWebRestAPI';
  let path = `/resources${query.command}`;
  let myInit = {
    headers: {
      Authorization: `Bearer ${(await Auth.currentSession())
        .getIdToken()
        .getJwtToken()}`,
    },
  };

  return API.get(apiName, path, myInit)
    .then((response) => {
      return wrapResponse(processor(response, query.params), false);
    })
    .catch((error) => {
      return wrapResponse(error, true);
    });
}
Example #8
Source File: AgentAssist.js    From chime-voiceconnector-agent-assist with MIT No Attribution 6 votes vote down vote up
async componentDidMount() {
    const transcript = await this.readTranscriptPaginationAndUpdate();
    this.setState({ transcript: transcript });

    const observable = await API.graphql(graphqlOperation(anncTranscript));
    const addSegmentToState = segment => {
      this.setState(state => {
        const updatedTranscript = state.transcript.slice();
        updatedTranscript.push(segment);
        return {
          transcript: updatedTranscript,
        };
      });
    };

    const updateTranscript = data => {
      const segment = data.value.data.onAnnounceCreateTranscriptSegment;
      addSegmentToState(segment);
      return;
    };

    observable.subscribe({
      next: updateTranscript,
      complete: console.log,
      error: console.error,
    });
  }
Example #9
Source File: AgentAssist.js    From chime-voiceconnector-agent-assist with MIT No Attribution 6 votes vote down vote up
async readTranscriptPaginationAndUpdate() {
    let transcript = [];
    const firstPage = await API.graphql(graphqlOperation(readTranscript));
    let nextToken = firstPage.data.listTranscriptSegments.nextToken;

    transcript = transcript.concat(firstPage.data.listTranscriptSegments.items);

    while (nextToken !== null) {
      const nextPage = await API.graphql(
        graphqlOperation(readTranscript, { nextToken: nextToken })
      );
      nextToken = nextPage.data.listTranscriptSegments.nextToken;
      transcript = transcript.concat(nextPage.data.listTranscriptSegments.items);
    }

    return transcript;
  }
Example #10
Source File: Dashboard.js    From aws-amplify-identity-broker with MIT License 6 votes vote down vote up
/*
	 * API call to get the Apps (Clients) for Single Sign On (SSO)
	 * Each App will shown with Logo, Name and a Link to LogbackUri
	 */
	getClients() {
		const apiName = 'amplifyIdentityBrokerApi';
		const path = '/clients';

		API
			.get(apiName, path)
			.then(response => {
				this.setState({ registeredClients: response });
			})
			.catch(err => {
				console.log(err);
				this.setState({
					snackBarOps: {
						type: 'error',
						open: true,
						vertical: 'top',
						horizontal: 'center',
						autoHide: 3000,
						message: I18n.get("DASHBOARD_ERROR_MESSAGE")
					}
				});
			});
	}
Example #11
Source File: App.js    From react-admin-amplify-demo with MIT License 6 votes vote down vote up
// Get the demo user avatar
authProvider.getIdentity = async () => {
  try {
    const userData = await API.graphql(
      graphqlOperation(queries.getUser, { id: "demo" })
    );

    const url = await Storage.get(userData.data.getUser.picture.key);

    return {
      id: "demo",
      fullName: "Demo",
      avatar: url,
    };
  } catch (e) {
    console.log(e);
  }
};
Example #12
Source File: GraphQLHandler.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
addAccounts = (params) => {
  return API.graphql(graphqlOperation(mutations.addAccounts, params));
}
Example #13
Source File: GraphQLHandler.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
getAccounts = () => {
  return API.graphql(graphqlOperation(queries.getAccounts, {}));
}
Example #14
Source File: GraphQLHandler.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
getAccount = (account) => {
  return API.graphql(graphqlOperation(queries.getAccount, account));
}
Example #15
Source File: App-03.js    From workshop-aws-getting-started-amplify with MIT License 5 votes vote down vote up
async componentDidMount(){
    var result = await API.graphql(graphqlOperation(listNotes));
    this.setState( { notes: result.data.listNotes.items } )
  }
Example #16
Source File: GraphQLHandler.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
addRegions = (params) => {
  return API.graphql(graphqlOperation(mutations.addRegions, params));
}
Example #17
Source File: GraphQLHandler.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
deleteRegions = (params) => {
  return API.graphql(graphqlOperation(mutations.deleteRegions, params));
}
Example #18
Source File: GraphQLHandler.js    From aws-perspective with Apache License 2.0 5 votes vote down vote up
deleteAccounts = (accountIds) => {
  return API.graphql(graphqlOperation(mutations.deleteAccounts, accountIds));
}
Example #19
Source File: Distributor.js    From training-distribute-licensecode-app with Apache License 2.0 5 votes vote down vote up
distributeLicenseCode() {

        // 画面初期化
        this.initDisplay();

        let email = this.state.email;
        let error = false;

        if (email == null || email === "") {
            this.setState({
                emailMessage: "メールアドレスを入力してください。"
            });
            error = true;
        }

        if (error) {
            return;
        }

        // Task: API Call
        console.log("Call LicenseCodeDistributor API");
        let apiName = 'LicenseCodeDistributorAPI';
        let path = `/license-codes`;
        let postData = {
            headers: {},
            body: {
                "email": email
            },
            response: true
        };
        API.post(apiName, path, postData).then(response => {
                var result = response.data;
//                console.log("API call Post is succeeded!", result);
                this.setState({
                    course: result.course,
                    licenseCode: result.licenseCode,
                    apiMessage: result.message
                });
            })
            .catch(err => {
                this.setState({
                    errMessage: "エラーが発生しました。"
                })
                console.log("api call error: ", err);
            });
    }
Example #20
Source File: App-05.js    From workshop-aws-getting-started-amplify with MIT License 5 votes vote down vote up
async componentDidMount() {
    var result = await API.graphql(graphqlOperation(listNotes));
    this.setState({ notes: result.data.listNotes.items });
  }
Example #21
Source File: App-04.js    From workshop-aws-getting-started-amplify with MIT License 5 votes vote down vote up
async componentDidMount() {
    var result = await API.graphql(graphqlOperation(listNotes));
    this.setState({ notes: result.data.listNotes.items });
  }
Example #22
Source File: Notes.js    From aws-amplify-quick-notes with MIT No Attribution 5 votes vote down vote up
NotesComponent = () => {
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    const fetchNotes = async () => {
      const result = await API.graphql(graphqlOperation(listNotes));

      setNotes(
        result.data.listNotes.items.sort((a, b) => {
          if (a.updatedAt > b.updatedAt) return -1;
          else return 1;
        })
      );
    };

    fetchNotes();
  }, []);

  return (
    <Container>
      {notes.map(note => (
        <Note
          key={note.id}
          {...note}
          onSaveChanges={async values => {
            const result = await API.graphql(
              graphqlOperation(updateNote, {
                input: {
                  ...note,
                  ...values
                }
              })
            );

            setNotes(
              notes.map(n => {
                return n.id === note.id ? result.data.updateNote : n;
              })
            );
          }}
          onDelete={async () => {
            await API.graphql(
              graphqlOperation(deleteNote, {
                input: {
                  id: note.id
                }
              })
            );

            setNotes(notes.filter(n => n.id !== note.id));
          }}
        />
      ))}
    </Container>
  );
}
Example #23
Source File: CCPData.js    From aws-amplify-connect with MIT No Attribution 5 votes vote down vote up
componentDidMount() {
    // eslint-disable-next-line no-undef
    connect.agent(function(agent) {

      agent.onOffline(function(agent) {
        this.setState({phonenumber: '0'});
        this.setState({ items: '' })
      }.bind(this));

      agent.onRoutable(function(agent) {
        this.setState({phonenumber: '0'});
        this.setState({ items: '' })
      }.bind(this));

    }.bind(this))

    // eslint-disable-next-line no-undef
    connect.contact(function(contact) {

      contact.onIncoming(function(contact) {
      }.bind(this));

      contact.onRefresh(function(contact) {
      }.bind(this));

      contact.onAccepted(function(contact) {
      }.bind(this));

      // Call established
      contact.onConnected(function(contact) {
      }.bind(this));

      // call ended
      contact.onEnded(function() {
      }.bind(this));

      // Triggered for the normal inbound calls.
      contact.onConnecting(function(contact) {
      }.bind(this));

      // Triggered for the Queue callbacks.
      contact.onIncoming(async function() {
        console.log(`onConnected(${contact.getContactId()})`);
        var attributeMap = contact.getAttributes();
        var phone = JSON.stringify(attributeMap["IncomingNumber"]["value"]);
        phone = phone.replace(/"/g, '');
        console.log(phone);
        //window.alert("Customer's phone #: " + phone);
        this.setState({phonenumber: phone});

        // api call
        if (this.state.phonenumber !== 0){
          try {
            const items = await API.get('api604c21a1', ('/telephonenumber/' + this.state.phonenumber))
            console.log(items)
            this.setState({ items: items })
          } catch (error) {
            console.log(error)
            //if (error.response.status === 404)
            //{
              this.setState({ items: '' })
            //}
          }
        }
        
        console.log(this.state.phonenumber);
      }.bind(this));
    }.bind(this));
  }
Example #24
Source File: Canvas.js    From aws-amplify-appsync-graphql-real-time-canvas with MIT No Attribution 5 votes vote down vote up
componentDidMount() {
    const canvas = {
      id: this.id,
      clientId: this.clientId,
      data: {
        ...this.state,
        lines: []
      }
    }
    // Create the canvas. If canvas is already created, retrieve the data & draw previous canvas
    API.graphql(graphqlOperation(createCanvas, { input: canvas }))
      .then(d => console.log('canvas created :', d))
      .catch(err => {
        if (err.errors[0].data.id === this.id) {
          const d = err.errors[0].data.data
          this.canvas.loadSaveData(d)
        }
      })
    window.addEventListener('mouseup', (e) => {
      // If we are clicking on a button, do not update anything
      if (e.target.name === 'clearbutton') return 
      this.setState({
        brushColor: rand()
      })
      const data = this.canvas.getSaveData()
      const p = JSON.parse(data)
      const length = p.lines.length
      this.lineLength = length

      const canvas = {
        id: this.id,
        clientId: this.clientId,
        data
      }
      // Save updated canvas in the database
      API.graphql(graphqlOperation(updateCanvas, { input: canvas }))
        .then(c => {
          console.log('canvas updated!')
        })
        .catch(err => console.log('error creating: ', err))
    })
    API.graphql(graphqlOperation(onUpdateCanvas))
      .subscribe({
        next: (d) => {
          const data = JSON.parse(d.value.data.onUpdateCanvas.data)
          const length = data.lines.length
          if (length === 0) {
            // If there is no canvas data, clear the canvas
            const data = this.canvas.getSaveData()
            const parsedData = JSON.parse(data)
            const newData = {
              ...parsedData,
              lines: []
            }
            const newCanvas = JSON.stringify(newData)
            this.canvas.loadSaveData(newCanvas)
            return
          }
          if (this.lineLength === length || length === Number(0)) return
          // Draw new lines to canvas
          const last = data.lines[length -1]
          this.canvas.simulateDrawingLines({ lines: [last] })
        }
      })
  }
Example #25
Source File: Record.js    From aws-amplify-quick-notes with MIT No Attribution 4 votes vote down vote up
RecordComponent = props => {
  const [isRecording, setIsRecording] = useState(false);
  const [showRecordingEditor, setShowRecordingEditor] = useState(false);
  const [recordingText, setRecordingText] = useState("");
  const [isConverting, setIsConverting] = useState("");
  const [micStream, setMicStream] = useState();
  const [audioBuffer] = useState(
    (function() {
      let buffer = [];
      function add(raw) {
        buffer = buffer.concat(...raw);
        return buffer;
      }
      function newBuffer() {
        console.log("reseting buffer");
        buffer = [];
      }

      return {
        reset: function() {
          newBuffer();
        },
        addData: function(raw) {
          return add(raw);
        },
        getData: function() {
          return buffer;
        }
      };
    })()
  );

  const startRecording = async () => {
    const stream = await window.navigator.mediaDevices.getUserMedia({
      video: false,
      audio: true
    });
    const startMic = new mic();

    startMic.setStream(stream);
    startMic.on("data", chunk => {
      var raw = mic.toRaw(chunk);
      if (raw == null) {
        return;
      }
      audioBuffer.addData(raw);
    });

    setMicStream(startMic);
    setIsRecording(true);
  };

  const stopRecording = async () => {
    micStream.stop();
    setIsRecording(false);
    setIsConverting(true);

    const buffer = audioBuffer.getData();
    const result = await Predictions.convert({
      transcription: {
        source: {
          bytes: buffer
        }
      }
    });

    setMicStream(null);
    audioBuffer.reset();
    setRecordingText(result.transcription.fullText);
    setIsConverting(false);
    setShowRecordingEditor(true);
  };

  return (
    <Container>
      <div
        css={css`
          position: relative;
          justify-content: center;
          align-items: center;
          width: 120px;
          height: 120px;
        `}
      >
        <div
          css={[
            css`
              width: 100%;
              height: 100%;
              top: 0;
              left: 0;
              position: absolute;

              border-radius: 50%;
              background-color: #74b49b;
            `,
            isRecording || isConverting
              ? css`
                  animation: ${pulse} 1.5s ease infinite;
                `
              : {}
          ]}
        />
        <div
          css={css`
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            position: absolute;
            border-radius: 50%;
            background-color: #74b49b;
            display: flex;
            cursor: pointer;
          `}
          onClick={() => {
            if (!isRecording) {
              startRecording();
            } else {
              stopRecording();
            }
          }}
        >
          {isConverting ? (
            <FaMicrophoneAltSlash
              size={50}
              style={{ margin: "auto" }}
            />
          ) : isRecording ? (
            <FaMicrophone
              size={50}
              style={{ margin: "auto" }}
            />
          ) : (
            <FaMicrophoneAlt
              size={50}
              style={{ margin: "auto" }}
            />
          )}
        </div>
      </div>
      {showRecordingEditor && (
        <RecordingEditor
          text={recordingText}
          onDismiss={() => {
            setShowRecordingEditor(false);
          }}
          onSave={async data => {
            await API.graphql(graphqlOperation(createNote, { input: data }));
            props.setTabIndex(0);
          }}
        />
      )}
    </Container>
  );
}
Example #26
Source File: index.js    From InstagramClone with MIT License 4 votes vote down vote up
StoryScreen = () => {

  const [stories, setStories] = useState([]);
  const [activeStoryIndex, setActiveStoryIndex] = useState(null);

  const route = useRoute();

  useEffect(() => {
    fetchStories();
    setActiveStoryIndex(0);
  }, []);

  const fetchStories = async () => {
    try {
      const storiesData = await API.graphql(graphqlOperation(listStorys));
      console.log(storiesData);
      setStories(storiesData.data.listStorys.items);
    } catch (e) {
      console.log('error fetching stories');
      console.log(e)
    }
  }

  const handleNextStory = () => {
    if (activeStoryIndex >= stories.length - 1) {
      return;
    }
    setActiveStoryIndex(activeStoryIndex + 1);
  }

  const handlePrevStory = () => {
    if (activeStoryIndex <= 0) {
      return;
    }
    setActiveStoryIndex(activeStoryIndex - 1);
  }

  const handlePress = (evt) => {
    const x = evt.nativeEvent.locationX;
    const screenWidth = Dimensions.get('window').width;

    if (x < screenWidth / 2) {
      handlePrevStory();
    } else {
      handleNextStory();
    }
  }

  if (!stories || stories.length === 0) {
    return (
      <SafeAreaView>
        <ActivityIndicator />
      </SafeAreaView>
    )
  }

  const activeStory = stories[activeStoryIndex];

  return (
    <SafeAreaView style={styles.container}>
      <TouchableWithoutFeedback onPress={handlePress}>
        <ImageBackground source={{uri: activeStory.image}} style={styles.image}>
          <View style={styles.userInfo}>
            <ProfilePicture uri={activeStory.user.image} size={50} />
            <Text style={styles.userName}>{activeStory.user.name}</Text>
            <Text style={styles.postedTime}>{activeStory.createdAt}</Text>
          </View>
          <View style={styles.bottomContainer}>
            <View style={styles.cameraButton}>
              <Feather name="camera" size={30} color={'#ffffff'}  />
            </View>
            <View style={styles.textInputContainer}>
              <TextInput
                style={styles.textInput}
                editable
                placeholder="Send message"
                placeholderTextColor={"white"}
              />
            </View>
            <View style={styles.messageButton}>
              <Ionicons name="paper-plane-outline" size={35} color={"#ffffff"}/>
            </View>
          </View>
        </ImageBackground>
      </TouchableWithoutFeedback>
    </SafeAreaView>
  )
}
Example #27
Source File: LoginForm.js    From react-admin-amplify-demo with MIT License 4 votes vote down vote up
LoginForm = (props) => {
  const { redirectTo, className } = props;
  const [loading, setLoading] = useSafeSetState(false);
  const login = useLogin();
  const translate = useTranslate();
  const notify = useNotify();
  const [demoUser, setDemoUser] = useState(null);

  useEffect(() => {
    if (demoUser) {
      return;
    }

    async function getDemoUser() {
      const userData = await API.graphql({
        query: getUser,
        variables: { id: "demo" },
        authMode: "AWS_IAM",
      });

      const { username, password } = userData.data.getUser;

      setDemoUser({ username, password });
    }

    getDemoUser();
  });

  if (!demoUser) {
    return null;
  }

  const submit = (values) => {
    setLoading(true);
    login(values, redirectTo)
      .then(() => {
        setLoading(false);
      })
      .catch((error) => {
        setLoading(false);
        notify(
          typeof error === "string"
            ? error
            : typeof error === "undefined" || !error.message
            ? "ra.auth.sign_in_error"
            : error.message,
          {
            type: "warning",
            messageArgs: {
              _:
                typeof error === "string"
                  ? error
                  : error && error.message
                  ? error.message
                  : undefined,
            },
          }
        );
      });
  };

  return (
    <StyledForm
      onSubmit={submit}
      mode="onChange"
      noValidate
      className={className}
      defaultValues={demoUser}
    >
      <CardContent className={LoginFormClasses.content}>
        <TextInput
          autoFocus
          source="username"
          label={translate("ra.auth.username")}
          validate={required()}
          fullWidth
        />
        <TextInput
          source="password"
          label={translate("ra.auth.password")}
          type="password"
          autoComplete="current-password"
          validate={required()}
          fullWidth
        />

        <Button
          variant="contained"
          type="submit"
          color="primary"
          disabled={loading}
          fullWidth
          className={LoginFormClasses.button}
        >
          {loading ? (
            <CircularProgress
              className={LoginFormClasses.icon}
              size={19}
              thickness={3}
            />
          ) : (
            translate("ra.auth.sign_in")
          )}
        </Button>
      </CardContent>
    </StyledForm>
  );
}