How to import global variable in Ember? - javascript

I am new to Ember, and am trying to use a global variable in the config / environment file to then import it into several adapters and models. I need this to change the variable in one place, instead of editing each file.
In this case, the global variable is a string with the address of the api server. The variable is named apiRoot. I tried to use the following configuration, but it does not work. Please tell me what needs to be done, if this is possible in the Ember, or maybe there is another way? Thanks for any help!
Environment File:
'use strict';
module.exports = function(environment) {
let ENV = {
modulePrefix: 'front',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
},
EXTEND_PROTOTYPES: {
Date: false
}
},
APP: {
}
};
if (environment === 'development') {
}
if (environment === 'test') {
ENV.locationType = 'none';
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
}
ENV.apiRoot = 'http://localhost:5555/api';
return ENV;
};
Adapter:
import RESTAdapter from '#ember-data/adapter/rest';
import ENV from '../../config/environment';
export default RESTAdapter.extend({
host: ENV.apiRoot,
pathForType() {
return "posts";
}
});

The problem is that your relative path probably refers to the /config/environment file outside of your appfolder. But it should refer to config/environment inside your app folder, a file that does not exist in your filesystem!
The reason for that is that you are not importing the config/environment file from the file system. Because that file does not exist in the browser. Instead ember-cli will execute that file during build time and send only the resulting JSON to your browser an make it avaliable at config/environment. But for all path in the browser the app folder is the root of your project. You can not import something outside the app folder.
And so your config/environment JSON that ember-cli produced will be basically moved into the app folder.

Related

BackEndUrl is undefined

I created a plugin, which should post some data to my backend. I tried to set up some backend url config. I checked the URl within my plugin with "console.log(...)" as u can see withn my code (in sendDataToBackEnd.js). But i getting following output "undefined".This is the error: "Error message: Cannot read property 'backEndUrl' of null"
Project structure:
project1
public
backend-config.js
faviocon.ico
index.html
src
App.vue
main.js
config
backEndUrlConfig.js
plugin
sendDataToBackEnd.js
Therefore I created backend-config.js within in Folder "public"
(function (window) {
window._backendconfig = {
urlBackend: `http://localhost:8090/api/auth/event`,
}
}(this));
My config.js looks like this:
export default { ...window._backendconfig }
And my PLugin "sendDataToBackEnd.js" looks like this:
import url from '../../config/backendURLconfig';
var backEndUrl = url.urlBackend;
console.log(backEndUrl)
const sendDatatoBackEnd = {}
sendDataToBackEnd.install = function (Vue){
{Method to send Data to my Backend}
}
export default sendDatatoBackEnd;
You're mixing using global scope JS (setting a property on window) in your config file with module style JS in your sendDataToBackEnd.js file (importing and exporting from modules).
You either need to export something from config (best option if you're using modules), or just access it from the window.
backendURLconfig.js
const config = {
urlBackend: `http://localhost:8090/api/auth/event`,
}
export default config
sendDataToBackEnd.js
import config from '../config/backendURLconfig';
var backEndUrl = config.urlBackend;
console.log(backEndUrl)
const sendDatatoBackEnd = {}
vuePlugin.install = function (Vue){
{Method to send Data to my Backend}
}
export default sendDatatoBackEnd;

AWS QLDB [ERROR] [Node.js QLDB Sample Code] Unable to create the ledger: ConfigError: Missing region in config

AWS QLDB CreateLedger.js throwing error.
~repo/amazon-qldb-dmv-sample-nodejs$ node dist/CreateLedger.js
[LOG][Node.js QLDB Sample Code] Creating a ledger named: vehicle-registration...
[AWS qldb undefined 0.005s 0 retries] createLedger({ Name: 'vehicle-registration', PermissionsMode: 'ALLOW_ALL' })
[ERROR][Node.js QLDB Sample Code] Unable to create the ledger: ConfigError: Missing region in config.
How to update region in nodejs Typescript code in CreateLedger.js
https://docs.aws.amazon.com/qldb/latest/developerguide/getting-started.nodejs.step-1.html
I want to add region in CreateLeger.TS file
import { QLDB } from "aws-sdk";
import {
CreateLedgerRequest,
CreateLedgerResponse,
DescribeLedgerRequest,
DescribeLedgerResponse,
} from "aws-sdk/clients/qldb";
import { LEDGER_NAME } from "./qldb/Constants";
import { error, log } from "./qldb/LogUtil";
import { sleep } from "./qldb/Util";
const LEDGER_CREATION_POLL_PERIOD_MS = 10000; const ACTIVE_STATE =
"ACTIVE";
export async function createLedger(ledgerName: string, qldbClient:
QLDB): Promise<CreateLedgerResponse> {
log(`Creating a ledger named: ${ledgerName}...`);
const request: CreateLedgerRequest = {
Name: ledgerName,
PermissionsMode: "ALLOW_ALL"
}
const result: CreateLedgerResponse = await
qldbClient.createLedger(request).promise();`enter code here`
log(`Success. Ledger state: ${result.State}.`);
return result; }
In which section I can add the region. So generated
dist/createLedger.js file have the changes
You can set the region in your JavaScript code using the Global Configuration Object. Update the AWS.Config global configuration object as shown here:
AWS.config.update({region: 'us-east-1'});
Alternatively, you could set an environment variable in your shell:
export AWS_REGION=us-east-1
You can find all options in Setting the AWS Region.
After some try I got the answer.
you can update config in this file ~src/qldb/logutil.ts
import { config } from "aws-sdk";
config.logger = console;
config.update({region: 'us-east-1'});
One note on this: The node.js SDK doesn't by default load the shared config file which stores your region configuration among other things. I've found this confusing at times since some of the other SDKs e.g. boto3 do that by default.
You have to set the environment variable AWS_SDK_LOAD_CONFIG=1 to load it.
This shared config file is created e.g. when you go through the aws configure steps in the aws-cli.
Related posts:
How to Load config from ~/.aws/config

API client in Javascript

I need a little help to solve a problem in my project.
Scenario:
First: I have a SPA web site that is being developed in Vue.js.
Second: I also have a Web API spec in Swagger that I want to use to generate my client code in Javascript.
Lastly: I'm using swagger-codegen-cli.jar for that.
What I've done until now
1 - Download the last swagger-codegen-cli.jar stable version with javascript support:
curl http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.4.7/swagger-codegen-cli-2.4.7.jar -o swagger-codegen-cli.jar
2 - Generate the client code using:
java -jar swagger-codegen-cli.jar generate -i http://192.168.0.85:32839/api/swagger/v1/swagger.json -l javascript -o ./web_api_client/
3 - Add the generated module to my project:
"dependencies": {
// ...
"vue": "^2.6.10",
"vue-router": "^3.0.3",
"web_api_client": "file:./web_api_client"
},
4 - Execute npm install. Apparently, it's working fine.
5 - At this moment I faced the problem. For some reason, the module generated isn't loaded completely.
export default {
name: 'home',
components: {
HelloWorld
},
mounted() {
var WebApiClient = require("web_api_client");
var defaultClient = WebApiClient.ApiClient.instance;
var oauth2 = defaultClient.authentications["oauth2"];
oauth2.accessToken = "YOUR ACCESS TOKEN";
var apiInstance = new WebApiClient.VersaoApi();
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
console.log('API called successfully. Returned data: ' + data);
}
};
apiInstance.apiVersaoGet(callback);
}
}
6 - The line var WebApiClient = require("web_api_client"); is working without any error, however, not working 100%. The instance of the module has been created but empty. For instance, WebApiClient.ApiClient is always undefined.
7 - I took a look at the generated code and I think the problem is related with the way the module is being loaded.
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'api/VersaoApi'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('./ApiClient'), require('./api/VersaoApi'));
}
}(function(ApiClient, VersaoApi) {
'use strict';
// ...
In this code, neither of ifs blocks are executed.
Has someone faced a problem like that?
Some advice?
Many thanks, folks.
Solution
After a while trying to fix the problem with require("web_api_client"); I decided to use ES6 instead ES5.
I found an option in swagger-codegen-cli.jar to generate the client code using ES6 as shown below:
java -jar swagger-codegen-cli.jar generate -i http://192.168.0.85:32839/api/swagger/v1/swagger.json -l javascript --additional-properties useES6=true -o ./web_api_client/
Using ES6 I was able to import the javascript module direct from the generated source as shown in the code below.
import WebApiClient from "./web_api_client/src/index";
let defaultClient = WebApiClient.ApiClient.instance;
defaultClient.basePath = 'http://192.168.0.85:32839';
// Configure OAuth2 access token for authorization: oauth2
let oauth2 = defaultClient.authentications["oauth2"];
oauth2.accessToken = "YOUR ACCESS TOKEN";
let apiInstance = new WebApiClient.VersaoApi();
apiInstance.apiVersaoGet((error, data, response) => {
if (error) {
console.error(error);
} else {
console.log("API called successfully. Returned data: " + data + response);
}
});
When I first ran the code I got an error because the module WebApiClient generated didn't have the keyword default in the export block.
Original generated code
export {
/**
* The ApiClient constructor.
* #property {module:ApiClient}
*/
ApiClient,
// ...
Alter changed
export default {
/**
* The ApiClient constructor.
* #property {module:ApiClient}
*/
ApiClient,
// ...
Now everything is working fine.

Unable to load module with extention js in TypeScript and Systemjs

Get request by Systemjs is not adding extention .js to the url.
These are my TypeScript Classes
customer.ts
import {Address} from "./Address";
export class Customer {
private _customerName: string = "";
public CustomerAddress: Address = new Address();
public set CustomerName(value: string) {
if (value.length == 0) {
throw "Customer Name is required";
}
this._customerName = value;
}
public get CustomerName() {
return this._customerName;
}
Validate(): boolean {
return this._customerName != '';
}
}
address.ts
export class Address {
public Street1: string = "";
}
using following Systemjs init code
System.config({
defaultExtension: 'js',
});
System.import("Customer.js").then(function (exports) {
var cust = new exports.Customer();
});
Customer.js is loaded successfully but Address.js is not.
The GET request for Address.js does not contains .js extention
resulting following request in console
GET http://localhost:65401/Address 404 (Not Found).
I have tried to update following code in customer.ts to following
import {Address} from "./Address.js";
But it is syntactically wrong and it shows error in VS2013.
How can i force Systemjs to add extension ".js" to the GET request.
Thanks
The defaultExtension keyword is not a top level config option. It needs to be under packages directive, see: https://github.com/systemjs/systemjs/blob/master/docs/config-api.md#packages
That's why it's ignored and SystemJS doesn't append the extension. You can define one "global" package which is probably the easiest way to make sure the extension is always appended to every import path:
SystemJS.config({
packages: {
'.': {
defaultExtension: 'js'
}
}
});

Vue.js exclude settings file from being bundled

I am using the vue-webpack template and I have created a settings.json file to store environment variables that should be changed when installing the script.
My settings.json (just store the absolute path to the API server):
{
"apiURL": "//localhost/app/server/API"
}
How can I keep the file from being minified/bundled in the production version such that I can change it and the updated file will be used next time the app is accessed (without having to build it again) ?
In my app I use this file via require:
const SETTINGS = require('../settings.json');
I understand that by requireing it webpack will bundle it as a module, but how can I include it in my app such that the settings file will still be a separated file in the production build that I can edit.
Is there a better format/way to store those settings (so that they can be edited in production without re-building) ?
You can define those settings in an object that can be referenced in the externals configuration in webpack.config.js.
The externals configuration option provides a way of excluding
dependencies from the output bundles. Instead, the created bundle
relies on that dependency to be present in the consumer's environment.
Example:
externals: {
appSettings: "appSettings",
"window.appSettings": "appSettings"
}
Where appSettings is a global variable containing the environment variables you want to manipulate.
Alternatively, if you do not like that method that exposes the settings in the global object, you can do the following:
Export a variable with the default settings, which will be included in webpack bundle.
export var appSettings = {
currentSettings: "",
settings: {},
getString: function(strName) {
var sett = this.currentSettings ?
this.settings[this.currentSettings] :
appDefaultStrings;
if (!sett || !sett[strName]) sett = appDefaultStrings;
return sett[strName];
},
getSettings: function() { //Gets all available settings
var res = [];
res.push("");
for (var key in this.settings) {
res.push(key);
}
res.sort();
return res;
}
};
export var appDefaultStrings = {
apiURL: "//localhost/app/server/API"
//...
}
appSettings.settings["default"] = appDefaultStrings;
You can then require or import this variable and use it like so:
import appSettings from "../path/to/appSettings";
appSettings.getString("apiURL"); //"//localhost/app/server/API"
Now that you have your default settings up and running, we will create another file containing the custom settings.
import appSettings from "../path/to/appSettings";
export var appProductionSettings = {
apiUrl: "http://example.com"
//...
}
appSettings.settings["production"] = appProductionSettings;
The last thing you need to do is handle which settings you want to use. I have not used vue.js yet, but hopefully this will lead you in the right direction:
import appSettings from "../path/to/appSettings";
export class MyApp {
constructor() {
this.settingsValue = "";
}
get settings() {
return this.settingsValue;
}
set settings(value) {
this.settingsValue = value;
appSettings.currentSettings = value;
}
}
Change the settings:
import "../path/to/productionSettings";
var app = new MyApp();
app.settings = "production";
With this method you can create and use as many settings files as you want.

Categories

Resources