I'm trying to generate JS for my simple REST API like eg described here: doc. My example code:
import vibe.d;
import wbapi;
import std.array : appender;
import vibe.core.file;
void main()
{
// generate JS for access
auto test = appender!string;
auto settingsJS = new RestInterfaceSettings;
settingsJS.baseURL = URL("http://localhost/api/integration/");
generateRestJSClient!IfWhiteBlowerAPI(test, settingsJS);
}
and interface:
#path("/api/integration")
interface IfWhiteBlowerAPI
{
Json get();
string postDeaf(Json obj);
}
Everything is compiling without any problem but i can't find generated JS anywhere. Am i looking in wrong place - main tree of app project?
I get help on vibed IRC channel. There is appender which is "handling" generated JS data. After we generate it we need to save it to file manually, below working example:
import vibe.d;
import std.stdio;
import std.array : appender;
import vibe.core.file;
#path("/api/integration")
interface IfWhiteBlowerAPI
{
Json get();
string postDeaf(Json obj);
}
void main()
{
// generate JS for access
auto test = appender!string;
auto settingsJS = new RestInterfaceSettings;
settingsJS.baseURL = URL("http://localhost/api/integration/");
generateRestJSClient!IfWhiteBlowerAPI(test, settingsJS);
auto f = File("test.js", "w");
f.write(test.data);
f.close();
}
Related
Im currently developing a dApp and want to connect it with the sync2 wallet. Since there is no support for dart im trying to use js functions in a js file in in the web-folder like this:
function checkBalance(value) {
const connex = new Connex({
node: 'http://3.71.71.72:8669/',
network: 'test'
})
const queryAcc = value
const acc = connex.thor.account(queryAcc)
acc.get().then(accInfo => {
const vet = accInfo.balance / 1e18 // +" VET"
return vet
})
}
I then call it in flutter with
var a = js.context.callMethod("checkBalance",
["0x70aE85A2fF6030366F512DbcD60Be3828139b498"]);
The problem is (as far as i can tell) that i cant create the Connex Object ("Could not find name 'Connex'. Did you mean 'connex'?ts(2570)" if i hover over Connex)
I have included connex in index.html like this:
<script src="https://unpkg.com/#vechain/connex#2" ></script>
Why does that not work?
I think, because I'm so new to Node, I'm not quite understanding how to use an NPM package with my React project running on Node.
Just a quick explanation:
I have a React component that uploads a zip file through Node server scripts. This part is working great, but now the next step I'm working on is getting node to unzip it after upload into a temp folder..
I'm using "axios" to post, and "multer" to save to file system and "adm-zip" for the unzip portion.
Here's a quick look at my on submit post function within my React Component:
onSubmit = (e) => {
e.preventDefault();
const { description, selectedFile } = this.state;
let formData = new FormData();
formData.append('description', description);
formData.append('selectedFile', selectedFile);
console.log('form data ',formData)
let that = this;
axios.post('/', formData)
.then((result, req) => {
this.setState({imagePath: result.data.path})
this.setState({fileName: result.data.filename})
this.setState({fileUploadStatus:"Upload Successful.."})
Unzip.extract(result.data.filename);
})
.catch(function (error) {
console.log(error);
//alert('File upload failed. Please ensure you are uploading a .zip file only')
that.setState({fileUploadStatus:"Upload failed.. Please ensure you are uploading a .zip file only"})
})
}
This is what I've put on the top of the React Component :
import React, { Component } from 'react';
import axios from 'axios';
import Unzip from './unzip';
This is my "unzip.js" file:
var AdmZip = require('adm-zip');
// reading archives
module.exports = (function() {
var extract = function extract(fileName, cb){
zip = new AdmZip("../uploads/"+fileName);
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
if (zipEntry.entryName == "my_file.txt") {
console.log(zipEntry.getData().toString('utf8'));
}
});
// extracts everything
zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true);
};
});
So the part I'm struggling with is understanding how to write a node script javascript file) with functions/properties (getter, setter, etc) that can be accessed from my React component..
I tried something like this:
var AdmZip = require('adm-zip');
// reading archives
var extract = function(thePath) {
zip = new AdmZip("../uploads/"+thePath);
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
if (zipEntry.entryName == "my_file.txt") {
console.log(zipEntry.getData().toString('utf8'));
}
});
zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true);
// extracts everything
};
But I got errors saying the function did not exist.. so I realized that I might have to set it up as a Node Module with an export function, but I couldn't figure out how to get that to work either..
Can someone explain to me, the proper way to approach this type of external script (script that runs outside of React and returns or executes some kind of action)?
As I mentioned in some of my other recent questions, I'm a beginner with Node so please go easy on me :)
Thanks!
React is a frontend package. You can use tools like unzip on the backend side. for example with ExpressJS.
I am trying to execute a JavaScript SDK from within a Swift application. I am unable to find the file however. I added the file to the project using cmd + click project -> Add files to "projectName" -> Add file and move into projectName/ folder.
I am still unable to get the file and run it inside a JSContext.
Where am I going wrong?
Here is my code (isOK is just used for a test case):
import Foundation
import JavaScriptCore
public class Wrapper {
public var isOK: Bool
var jsContext: JSContext
init (pathToSdk: String) {
let virtualMachine = JSVirtualMachine()
self.jsContext = JSContext(virtualMachine: virtualMachine)
if let sdkBundle = Bundle.main.path(forResource: pathToSdk, ofType: "js") {
let bundleString = try! String(contentsOfFile: sdkBundle)
self.jsContext.evaluateScript(bundleString)
print("Successfully initialised JavaScript context")
self.isOK = true
} else {
print("Unable to fetch SDK bundle at path: \(pathToSdk)")
self.isOK = false
}
}
}
I call it in my test:
func testIsOK() {
let wrapper = Wrapper(pathToSdk: "sdk").isOK
XCTAssertEqual(wrapper, true)
}
And my folder structure:
Thanks and sorry if this is a silly question, I'm brand new to Swift.
i built an app on 1 page, and now i want to oragenize all of its functions and objects in seperate files and directories, and import them to the app.js file. but im having some problems with global objects, the the imported functions dosent recognize them.
example:
//app.js
const req_obj = require("./objectFile.js")
const tool = {
number:4
}
req_obj.obj.addFive() // this will print "cant read number of undefined"
//objectFile.js
const req_func = require("./function.js")
exports.obj = {
addFive:req_func.addFive
}
//function.js
exports.addFive = function(){
return tool.number + 5
}
i know that it might be that im doing all wrong, and this is not how you orgenize an app and call its function. i whould be really glad if some1 will explaine my how to orgenize an app, and call its functions the right way, if what i did is wrong.
The only possibility you have to get access to variables from multiple files is to have them in a separate file and export them like this:
// objects.js
const tool = {
number:4
}
exports.tool = tool
Which then makes your app.js look like:
//app.js
const req_obj = require("./objectFile.js")
const tool = require("./objects.js").tool
// this will read 9
console.log(req_obj.obj.addFive())
And your function.js then becomes:
const tool = require("./objects.js").tool
exports.addFive = function(){
return tool.number + 5
}
Hope it helps.
I am trying to update a canvas using a react component with processing done in a worker thread. I have all the hard parts working fine in EMCA5, but porting to React/Babel/JSX, my biggest hangup is the system no longer recognizes ArrayBuffer to pass data to the worker thread. The following code dies with 'TypeError: ArrayBuffer is not a constructor':
import React from 'react';
// import Calculater etc...
export default class CalculationDisplay extends React.Component {
componentDidMount() {
var buffer = new ArrayBuffer(100 * 100 * 4);
var view = new Uint32Array(buffer);
var calculator = new Calculator(view);
const ctx = this.refs.canvas.getContext('2d');
// worker calculation and display goes here...
}
render() {
return (
<canvas ref="canvas" width={600} height={600}/>
);
}
}
After a bunch of research into babel-polyfill and core-js, all variations I could think of on the following die the same way:
var ArrayBuffer = require('core-js/modules/es6.typed.array-buffer');
import ArrayBuffer from 'core-js/modules/es6.typed.array-buffer';
import { ArrayBuffer } from 'core-js/modules/es6.typed.array-buffer';
import { ArrayBuffer } from 'babel-polyfill';
The only thing I found that works so far is to forget any imports/requires and just access ArrayBuffer and it's ilk this way:
var buffer = new global.ArrayBuffer(100 * 100 * 4);
var view = new global.Uint32Array(buffer);
..this actually works and the display shows up on the page, but it seems ugly and I can't imagine this is the intended way to reference ArrayBuffer. Has anyone had success importing js ArrayBuffer and related classes so they can be accessed as expected?
..OK following zerkms suggestion I updated to:
import React from 'react';
import 'babel-polyfill';
// import Calculater etc...
export default class CalculationDisplay extends React.Component {
componentDidMount() {
var buffer = new ArrayBuffer(100 * 100 * 4);
var view = new Uint32Array(buffer);
. . .
..and it works without error - I guess I was getting too fancy with trying to import the classnames from babel-polyfill previously.