aws-amplify integration with Nativescript (angular) - axios

I am trying to integrate ams-amplify with NativeScript but I am not able to get it to work successfully.
import { Component, OnInit } from "#angular/core";
require("nativescript-nodeify");
var Amplify = require("aws-amplify");
#Component({
selector: "Home",
moduleId: module.id,
templateUrl: "./home.component.html"
})
export class HomeComponent implements OnInit {
constructor() {
// Use the component constructor to inject providers.
Amplify.configure({
Auth: {
// REQUIRED - Amazon Cognito Identity Pool ID
identityPoolId: 'xxxxx',
// REQUIRED - Amazon Cognito Region
region: 'xxxx',
// OPTIONAL - Amazon Cognito User Pool ID
userPoolId: 'xxxx',
// OPTIONAL - Amazon Cognito Web Client ID
userPoolWebClientId: 'xxxxx',
}
});
}
ngOnInit(): void {
}
}
But I am getting some "navigator is not defined" error.
JS: ERROR Error: Uncaught (in promise): ReferenceError: navigator is
not defined JS: ReferenceError: navigator is not defined JS: at
standardBrowserEnv
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/helpers/isURLSameOrigin.js:11:39)
JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/helpers/isURLSameOrigin.js:60:5)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/adapters/xhr.js:7:23)
JS: at require (:1:266) JS: at getDefaultAdapter
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/defaults.js:20:15)
JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/defaults.js:29:12)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/core/Axios.js:3:16)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/axios.js:5:13)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/index.js:1:78)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/aws-amplify/lib/API/RestClient.js:70:15)
If anyone has working code, please share.

The problem is with latest version of aws-amplify.
Changed it to "aws-amplify": "^0.2.9" version and everything working fine now :)
Edit: Working Solution with latest Amplify version
import * as storage from "nativescript-localstorage";
import { Buffer } from "buffer";
import "nativescript-nodeify";
global["window"] = {};
global["window"]["localStorage"] = storage;
global["window"]["addEventListener"] = args => {
return args;
};
global["window"]["navigator"] = {};
global["window"]["Buffer"] = Buffer;
global["window"]["setTimeout"] = setTimeout;
global["window"]["clearTimeout"] = clearTimeout;
global["navigator"] = {};
global["navigator"]["product"] = "ReactNative";
import Amplify, { Auth, Storage } from "aws-amplify";
import aws_config from "~/aws-exports";
Amplify.configure(aws_config);

Related

React App deployed in LWC component of salesforce

I have deployed React App in LWC component without using Aura container basically bundle react application with webpack as static resource and use them inside a LWC and able to render.
able to open individual stylesheet for debugging purpose.
Question: Not able to debug the code/not opening individual JS file/component in developer console.
lwcReactContainer.html
<template>
<div id="react-app-root"></div>
</template>
lwcReactContainer.js
import { LightningElement, wire } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import SPMLayoutEditor1 from '#salesforce/resourceUrl/SPMLayoutEditor1';
//import myStaticStyles from '#salesforce/resourceUrl/myStaticStyles';
import {
APPLICATION_SCOPE,
createMessageContext,
MessageContext,
publish,
releaseMessageContext,
subscribe,
unsubscribe,
} from 'lightning/messageService';
import getContactList from '#salesforce/apex/ContactController.getContactList';
export default class LWCReactContainer extends LightningElement {
renderedCallback() {
this.apiInProgress = true;
Promise.all([
loadScript(this, SPMLayoutEditor1 + '/FSLMAX_LayoutEditor/static/js/main.js'),
loadStyle(this, SPMLayoutEditor1 + '/FSLMAX_LayoutEditor/static/css/main.css'),
this.getUserInfo(), this.getContactList(), this.fetchObjectList()
]).then((data) => {
const contacts = data[3];
mount(this.template.querySelector('div'), { contacts });
});
}

Nuxt vuex - moving store from Vue

I have been fiddling with moving a tutorial I did in Vue to Nuxt. I have been able to get everything working, however I feel I'm not doing it the "proper way". I have added the Nuxt axios module, but wasnt able to get it working, so I ended up just using the usual axios npm module. Here is my store:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex)
Vue.use(VueAxios, axios)
export const state = () => ({
events: []
})
export const mutations = {
setEvents: (state, events) => {
state.events = events
}
}
export const actions = {
loadEvents: async context => {
let uri = 'http://localhost:4000/events';
const response = await axios.get(uri)
context.commit('setEvents', response.data)
}
}
I would like to know how to re-write this store using the #nuxtjs/axios module. I also didnt think I'd need to import vuex here, but if I dont, my app doesn't work.
Thanks for any help!
Using the #nuxtjs/axios module, you can configure axios inside your nuxt.config.js:
// nuxt.config.js
export default {
modules: [
'#nuxtjs/axios',
],
axios: {
// proxy: true
}
}
You can use it inside your store (or components) with this.$axios
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}

Using mongodb-stitch library in Angular 4

Im been trying the MongoDB Stitch service in Angular, so far Im able to use the service. However, the only way I could connect to the service is by including the js library hosted in AWS on the html page.
There is a mongodb-stitch npm package available and there are sample pages on mongodb tutorial on how to use it. But this is a pure JS library (no TS support) and I have tried several ways (using require, installing typings of the lib (not available), using #types) to no avail.
Anyone tried this on Ng4? Would love to have the steps you did to use the 'mongodb-stitch' package the create a service.
The other answer suggests instantiating a new instance of StitchClient which is something that MongoDB have explicitly advised against in the Official API Documentation - and with reason, since there is a factory method available for that purpose. So, (after installing mongodb-stitch), the following code would help you get started in component.ts
import { Component, OnInit } from "#angular/core";
import { StitchClientFactory } from "mongodb-stitch";
let appId = 'authapp-****';
#Component({
selector: "app-mongo-auth",
templateUrl: "./mongo-auth.component.html",
styleUrls: ["./mongo-auth.component.css"]
})
export class MongoAuthComponent implements OnInit {
mClient;
ngOnInit() {
this.mClient = StitchClientFactory.create(appId);
}
And you can then use this for whatever purpose you want, such as for implementing sign-in with Google
gLogin(){
this.mClient.then(stitchClient => {
stitchClient.authenticate("google");
})
not sure whether the question is still relevant considering it was asked two months ago but anyway...
As you pointed out you can use
npm install --save mongodb-stitch
to install the package and since there is no TS binding you can declare the stitch library as any
For example:
declare var stitch: any;
export class MyService implements OnInit {
db;
client;
ngOnInit() {
this.client = new stitch.StitchClient('<check the stitch app page for proper value>');
this.db = this.client.service('mongodb', 'mongodb-atlas').db('<the db name goes here>');
this.client.login();
}
save() {
this.db.collection('<collection name>').insertOne({key : 'value'}).then(() => console.log("All done"));
}
}
the previous answers are functional, but i wanna share a example using a service injectable.
service.ts
import { Injectable } from '#angular/core';
import { Jsonp, URLSearchParams } from '#angular/http';
import { StitchClientFactory } from "mongodb-stitch";
import 'rxjs/add/operator/map';
#Injectable()
export class Service {
constructor(private jsonp: Jsonp) { }
client;
connect(){
this.client = new StitchClientFactory.create("App ID"); // Slitch apps > Clients > App ID
this.client.then(stitchClient => stitchClient.login())
.then((stitchClient) => console.log('logged in as: ' + stitchClient))
.catch(e => console.log('error: ', e));
}
all() {
this.connect();
return this.client.then(stitchClient => {
let db = stitchClient.service('mongodb', 'mongodb-atlas').db("database Name"); // Slitch apps > mongodb-atlas > Name database.Collection
let itemsCollection = db.collection('name collection'); // Slitch apps > mongodb-atlas > Name database.Collection
console.log(itemsCollection.find().execute());
return itemsCollection.find().execute();
})
.then(result => {return result})
.catch(e => console.log('error: ', e));
}
}
after make the previous file, you must create a module to receive the data, so:
module.ts
import { Component, OnInit, Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { StitchClientFactory } from "mongodb-stitch";
import { Service } from 'service'; // previous code
declare var stitch: any;
#Component({
template: '
<ul class="demo-list-icon mdl-list">
<li class="mdl-list__item" *ngFor="let item of data | async">
<span class="mdl-list__item-primary-content">
<i class="material-icons mdl-list__item-icon">{{propiedad.nombre}}</i>
</span>
</li>
</ul>
'
})
export class MainComponent implements OnInit {
data: Observable<[]>;
constructor(private Service: service) {
}
ngOnInit() {
this.propiedades = this.Service.all();
}
}
important, you don´t must forget to add service on module.ts intitial declarations.
mongodb Atlas
mongodb-stitch vía NPM
Documentation mongoDB Stitch.
Sure!

Custom authorizer not called

I'm trying to implement a custom authorizer (using ember-cli and ember-cli-simple-auth) but the authorize method is not being called on any requests. The init function is being called and the message that appears in the console when there is no authorizer registered is no longer showing up. Here is the initializer code:
import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';
import ENV from '../config/environment';
ENV['simple-auth'] = ENV['simple-auth'] || {};
ENV['simple-auth'].authorizer = 'authorizer:custom';
ENV['simple-auth'].crossOriginWhiteList = [ENV.NET.API_ENDPOINT];
var CustomAuthorizer = Base.extend({
init: function () {
console.log('Intialize authorizer');
},
authorize: function(jqXHR, requestOptions) {
console.log('Authorize');
var token = this.get('session.token');
if(this.get('session.isAuthenticated') && !Ember.isEmpty(token)) {
authValue = "Token " + token;
jqXHR.setRequestHeader('Authorization', authValue);
}
}
});
export default {
name: 'authorization',
before: 'simple-auth',
initialize: function(container, application) {
console.log('Registered');
container.register('authorizer:custom', CustomAuthorizer);
}
};
Any help would be appreciated.
Problem here was something quite dumb: my casing of crossOriginWhitelist was incorrect.

Custom authenticator with Ember simple auth + Ember CLI

I'm trying to write a custom authenticator, similar to the one from this example in the docs. The goal is to be able to retrieve the currently logged in user via session.user.
I'm using Ember CLI, so in initializers/authentication.js I have
import Ember from 'ember';
var customAuthenticator = Ember.SimpleAuth.Authenticators.Devise.extend({
authenticate: function(credentials) {
debugger;
}
});
export default {
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.Session.reopen({
user: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return container.lookup('store:main').find('user', userId);
}
}.property('userId')
});
// register the custom authenticator so the session can find it
container.register('authenticator:custom', customAuthenticator);
Ember.SimpleAuth.setup(container, application, {
routeAfterAuthentication: 'landing-pages',
authorizerFactory: 'ember-simple-auth-authorizer:devise'
});
}
};
When I try to authenticate, I get the following error:
TypeError: Cannot read property 'authenticate' of undefined
at __exports__.default.Ember.ObjectProxy.extend.authenticate
Any idea why?
As of Simple Auth 0.6.4, you can now do something like:
index.html:
window.ENV['simple-auth'] = {
authorizer: 'simple-auth-authorizer:devise',
session: 'session:withCurrentUser'
};
initializers/customize-session.js:
import Ember from 'ember';
import Session from 'simple-auth/session';
var SessionWithCurrentUser = Session.extend({
currentUser: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return this.container.lookup('store:main').find('user', userId);
}
}.property('user_id')
});
export default {
name: 'customize-session',
initialize: function(container) {
container.register('session:withCurrentUser', SessionWithCurrentUser);
}
};
You would need to do something like this:
Em.SimpleAuth.Authenticators.OAuth2.reopen
serverTokenEndpoint: "http://myapp.com/token"
authenticate: (credentials) ->
new Em.RSVP.Promise (resolve, reject) =>
data =
grant_type: "password"
username: credentials.identification
password: credentials.password
#makeRequest(data).then (response) =>
# success call
, (xhr, status, error) ->
# fail call
What I think might be happening is that you are registering the authenticator with the application and not the authenticator itself?
The problem is that the AMD build does not currently automatically register the extension libraries' components (see https://github.com/simplabs/ember-simple-auth/issues/198). I'll change that in the next release and will probably also adopt the documentation to be more focussed on the AMD build instead of the browserified version. For the moment you'd have to run this in your initializer
container.register(
'ember-simple-auth-authorizer:devise',
Ember.SimpleAuth.Authorizers.Devise
);
container.register(
'ember-simple-auth-authenticator:devise',
Ember.SimpleAuth.Authenticators.Devise
);