Having trouble with requiring AWS in Javascript - javascript

I'm trying to implement DynamoDB in a Javascript file. I tried out multiple tutorials in succession to no avail. All I'm trying to do is make a query from within my Javascript code (which is being run in an HTML page). Unfortunately, my code doesn't even get up to that. It throws me errors when I try to require AWS-SDK. I installed aws-sdk with Node.js. After being confused by multiple tutorials, I ended up with the following code:
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://requirejs.org/docs/release/2.2.0/r.js"></script>
<script src="boom.js"></script>
</head>
<body></body>
</html>
JavaScript (boom.js):
require(['aws-sdk'], function (foo) {
var CONF = require("./super_secure_conf.json");
var AWS = require("aws-sdk");
function init(){
AWS.config = new AWS.Config({
access_key_id: CONF.AWS_ACCESS_KEY_ID,
secretAccessKey: CONF.AWS_SECRET_ACCESS_KEY,
region: "us-east-1"
});
DynamoDB = new AWS.DynamoDB();
}
});
The file "super_secret_conf.json" is a JSON file containing my AWS Credentials. I tried storing the credentials at ~/.aws/credentials previously, but that wasn't working. (Should credentials be a folder or file? I had tried saving my credentials in a blank file – without any extension. Just thought I'd mention.) So I followed another tutorial, which said to use the JSON method (and I am aware that it is very insecure) which is what you see here. I still get an error though:
Error: Module name "super_secure_conf.json" has not been loaded yet for context: _. Use require([])
All and any help is greatly appreciated.

You are requiring AWS twice, calling it foo the first time. And you aren't waiting for the callback from your config.json require call (or even passing it a callback function). I believe your code needs to change to look like this:
require(['aws-sdk', "./super_secure_conf.json"], function (AWS, CONF) {
function init(){
AWS.config = new AWS.Config({
access_key_id: CONF.AWS_ACCESS_KEY_ID,
secretAccessKey: CONF.AWS_SECRET_ACCESS_KEY,
region: "us-east-1"
});
DynamoDB = new AWS.DynamoDB();
}
});
However I'm not sure if the path "./super_secure_conf.json" is actually going to work. That looks like a path you would use for loading a file in a server-side NodeJS application, not a browser-side JavaScript application.
Note that the reason you have to load your config this way is because the ~/.aws/credentials method of loading an AWS config is not going to work for a JavaScript app running in a browser. I think you've been reading NodeJS tutorials which aren't going to translate perfectly to JavaScript in the browser. I would highly recommend you start by looking through the documentation for AWS SDK for JavaScript in the Browser, and in particular read the page on Configuring the SDK in the Browser.

Related

How to intercept file protocol and convert it to https in electron app

My question is similar to this issue. But the solution provided there does not address it.
I'm trying to integrate Tealium tags into my electron app. I have added the code snippet as per documentation as below:
<script type="text/javascript">
(function(a,b,c,d) {
a='//tags.tiqcdn.com/utag/ACCOUNT/PROFILE/ENVIRONMENT/utag.js';
b=document;c='script';d=b.createElement(c);d.src=a;
d.type='text/java'+c;d.async=true;
a=b.getElementsByTagName(c)[0];a.parentNode.insertBefore(d,a)})();
</script>
The above script in turn has calls to multiple utag.x.js. The issue is that the utag files are not locally available and hence the file protocol to locate these fails with ERR_FILE_NOT_FOUND.
I changed the value of variable 'a' to start with 'https' then utag.js is downloaded successfully but the next call to utag.x.js fails. To solve this I'm trying to intercept the file protocol using the API interceptFileProtocol().
app
.whenReady()
.then(() => {
protocol.interceptFileProtocol('file', (request, callback) => {
if (request.url.includes('utag')) {
console.log('UTAG request...');
request.url = `https://${request.url.slice('file://'.length)}`;
}
callback(request);
})
});
In the console I can see that the call is intercepted and the url gets updated. But the network call to download the resource still has the file protocol instead of https and hence get ERR_FILE_NOT_FOUND.
Am I correct in using the interceptFileProtocol or is there any other way to do it?

How to use libraries installed via <script> tags in React

I'm trying to create a Facebook Instant HTML5 application in React.
As per their Quick Start documentation, they want me to install their SDK using a script tag, like so:
<script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></script>
I've created my app using create-react-app. I've placed that snippet inside /public/index.html so it looks like:
...
<body>
<noscript>You need to enable javascript to run this app.</noscript>
<script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></script>
...
They also provide the following snippet:
// Once all assets are loaded, tells the SDK
// to end loading view and start the game
FBInstant.startGameAsync()
.then(function() {
// Retrieving context and player information can only be done
// once startGameAsync() resolves
var contextId = FBInstant.context.getID();
var contextType = FBInstant.context.getType();
var playerName = FBInstant.player.getName();
var playerPic = FBInstant.player.getPhoto();
var playerId = FBInstant.player.getID();
// Once startGameAsync() resolves it also means the loading view has
// been removed and the user can see the game viewport
game.start();
});
Which I've placed in src/index.tsx'.
This then gives me errors, saying:
'FBInstant' is not defined no-undef
Which likely means that the library is not being installed properly / brought into the proper namespace so that my React code can access it.
How can I get around this? Facebook tells me not to download and include it myself - they'll reject my app.
Important notes:
Do not download and add the SDK to your bundle as it will be rejected in later steps.
This is a new way to build games on Facebook and does not support the Graph API.
So it seems I must use these <script> tags. How can I make React recognise it?
Once you have added the fbinstant script tag in the index.html
In your src/index.tsx, Add this to the top (before your snippet):
const FBInstant = window.FBInstant;
As you explained, you're getting this error because the typescript compiler does not recognize FBInstant, Since it is not installed.
However in this case seems all you need is to make the compiler ignore these warning. The most suitable in my opinion is export it to a seperate js file (and not ts / tsx), since it is a javascript code. Than import it as any node module.
If you don't like this option, alternative methods can be:
including the SDK code on your index.html, right after your script tag
Using #ts-ignore to suppress typescript errors
define FBInstant before the SDK script (more about this here)
interface Window {
[key:string]: any; // Add index signature
}
const FBInstant = (window as Window)['FBInstant'];

Adobe Sign JS SDK

Adobe changed their GitHub from the last time we imported their latest code for the JS SDK. It used to have pre-generated Browser specific JS files that you copy paste into the code, now it uses Swagger auto generation into Node.Js files and wants the users to browserify it to use it in browser js.
TL:DR I don't know how to convert the node.js files into browser files
I have tried following all of the instructions that they have in their readme, but nothing seems to work. The only thing I haven't tried (which could be the key) is to write my code in a JS file with the node.js "require()" to import the js files, then browserify my code. If that's what I have to do then I unfortunately will not be able to upgrade.
Right now the code that I use to access the api is this
<!-- supplied by Adobe before -->
<script type="text/javascript" src="~/scripts/sha1-min.js"></script>
<script type="text/javascript" src="~/scripts/adobe-sign-sdk.js"></script>
<script type="text/javascript" src="~/scripts/superagent.min.js"></script>
<script type="text/javascript" src="~/scripts/validator.min.js"><</script>
async function GenerateAuthForm() {
var context = new AdobeSignSdk.Context();
//Initialize the Widget API
var agreementApi = new AdobeSignSdk.AgreementsApi(context);
//Get the Widget model
var widgetsModel = AdobeSignSdk.AgreementsModel;
var agreementsModel = AdobeSignSdk.AgreementsModel;
//Populate the access token
/**/
var agreementCreationInfo = new agreementsModel.DocumentCreationInfo();
//does more work below
and that is super easy to call and use.
I want to be able to do that same process, but with the updated version, so I can use Workflows rather than agreements.
EDIT:
I have tried to browserify the index.js located at /AdobeSignNodeJsSdk/src and it did combine all of the files, but I had no way to call it, or I didn't understand how to call it. I tried to call it as below
<script src="~/Scripts/bundle.js"></script>
<script>
var context = new SwaggerJsClient.ApiClient(); //this was undefined
var api = new context.WorkflowsApi()
//do stuff with the api or model
Furthermore in the file that was put through browserify, it references root.SwaggerJsClient.apiormethod, so I assumed that there is some way to call this, and I just don't know what it is.
I am closing this question as I figured out how to import the code properly using browserify like this
browserify -r ./index.js:AdobeSignSdk > bundle.js
then referencing it like
var adobeSignSdk = require('AdobeSignSdk');
var context = new adobeSignSdk.ApiClient();
And I would like to report that the "Latest version" after going through the code and determining how to use it, has significantly LESS functionality than the previous version. You cannot create a Workflow through 2.0, you can only get the existing ones, and their statuses. The previous release, 1.1.0 still doesn't work correctly when you try to create a workflow as they didn't include
customWorkflowAgreementCreationRequest.getDocumentCreationInfo()
so when you try to create one it fails with an error.
TypeError: customWorkflowAgreementCreationRequest.getDocumentCreationInfo is not a function
This is unfortunate as that is the feature I needed, and I will likely now have to switch my application from JS to the C# REST Api, something that needed to happen anyways, just waiting for when it wasn't so urgent.

Polymerfire: No default bucket found

I'm trying to upload data to the storage Bucket of my app but the line var uploadRef = firebase.storage().ref(); causes the following error:
Firebase Storage: No default bucket found. Did you set the 'storageBucket' property when initializing the app?
However (I think) I already initialized the app by placing the polymer <firebase-app> element in the body of my index.html like so:
<firebase-app
api-key="<my-api-key>"
auth-domain="<my-auth-domain>"
database-url="<my-database-url>"
storageBucket="<my-storageBucket-url>">
</firebase-app>
I also tried some solutions on the web and have checked:
that my App Engine APIs are enabled
that I have the App Engine app enabled
that firebase-storage#system.gserviceaccount.com is an owner on the storage bucket
By now i don't really know what else to try and would appreciate any help you can offer!
Turns out the polymerfire-version provided by the Google web-starter-kit was not the latest one. By the time I found that out I already used the firebase initialization snippet provided on the firebase homepage and therefore don't need the element anymore.
Now everything works fine.

Write a variable to a file in Javascript

This may be a copy.. but I'm not getting the thing I want from the answers I saw..
I just want to save a particular variable into a local file using Javascript. I know how to read a file.
I wrote this code..
<script>
var fs = require('fs');
fs.writeFile('http://localhost/online/hello.txt', 'Hello Node', function (err) {
if (err) throw err;
else
{
console.log('It\'s saved!');
}
});
</script>
What is the error here.. or is there a simple and straight-forward way of doing it..??
It seems you're trying to call node-js code from the browser. Although javascript can run in both the browser and on the server (node-js), those are separate systems.
Another thing you can do is google "HTML save file example" and see how this is typically implemented - by opening a save dialog for the user, getting his/her permission, etc. (otherwise any website could just write any file to your computer...).
You are writing NodeJS code for client side application. You must understand the difference between javascript on browser and javascript on NodeJS platform.
Javascript is a language just like C, Java and Python
V8 is a javascript engine to run the javascript application. It is something similar to JRE for Java.
Browser(Only Chrome) uses V8 engine for running javascript application. Other browsers use different javascript engine. Five years ago, there was only one possibility that javascript can only work on browser. You cannot use javascript for application programming like C and Java
NodeJS is a platform which uses V8 to enables developer to write javascript application just like C, Java program. NodeJS also has some inbuilt library for accessing file system,
networks, and much more utilities. One of the internal library in NodeJS is fs. It only works on NodeJS application, not on browser application.
This can be done pretty simply using jrpc-oo. jrpc-oo links the browser and nodejs using the JRPC2 protocol. jrpc-oo abstracts classes over JRPC so that either side (nodejs or the browser) can call eachother.
I have setup an example repo to do exactly this here. Use the writeToFile baranch. I will break out the important parts here.
First in nodejs, we write a class with a method to write input arguments to file. The method looks like so (from the file TestClass.js) :
const fs = require('fs');
class TestClass {
writeToFile(arg){
fs.writeFileSync('/tmp/browser.json',JSON.stringify(arg));
}
}
In the browser we inherit from the jrpc-oo class JRPCClient and call the server class TestClass and method writeToFile like so (from the file src/LitJRPC.js) :
import {JRPCClient} from '#flatmax/jrpc-oo/jrpc-client.js';
export class LitJRPC extends JRPCClient {
writeObjToFile(){
// create the argument we want to save to file
let dat={name:'var',value:10};
// Ask the server to execute TestClass.writeToFile with args dat
this.server['TestClass.writeToFile'](dat);
}
}
Finally we run the nodejs app and the web-dev-server and we look at the browser console and nodejs console to see what happened. You will see the browser variable dat saved to the file /tmp/browser.json
As we are using a secure websocket for jrpc, you will need to generate the certificate and clear the certificate with the browser before the app will work. If you don't want to worry about security then don't use secure websockets. Read the readme in the reference repo for more information on setup and usage.

Categories

Resources