Use Node envs in json file - json

Im using dotenv to declare my envs and then I import the m to the main file but I have a json file which needs the proccess.env but I don't want to hard code the API keys
Is there a way to the envs to the json file without hard coding them ?
from this
{
"accessKeyId": "ACCESS_KEY",
"secretAccessKey": "SECRET_KEY",
"region": "us-east-1"
}
to this
{
"accessKeyId": proccess.env.ACCESS_KEY,
"secretAccessKey": "SECRET_KEY",
"region": "us-east-1"
}

Instead of a JSON file you can create a javascript file and export the json object
module.exports = {
"accessKeyId": process.env.ACCESS_KEY,
"secretAccessKey": process.env.SECRET_KEY,,
"region": "us-east-1"
}
in your code you can directly require this file.

Related

Trying to generate a json asset file in Flutter

I have created a flutter web project and I am using flutter_azure_b2c package which uses asset json files, everything works fine when I run it.
it's shown like this
Now I want to generate these json config files automatically using env variables when I build the app.
Here is my json file format:
{
"client_id" : "",
"redirect_uri" : "",
"cache_location": "localStorage",
"interaction_mode": "redirect",
"authorities": [
{
"type": "B2C",
"authority_url":""
},
{
"type": "B2C",
"authority_url":""
}
],
"default_scopes": [
]
}
How can it be done?
I tried to write into the file when executing main.dart using this package https://pub.dev/packages/global_configuration but json values are not updated when I pass them in flutter_azure_b2c method

Ember JS FindAll returns undefined data

iam currently developing a contact management system web app using ember js for the front end .Iam using ember store for fetching the data from the api , while fetching json data using store.findAll() , iam getting the json array with the length of data as expected but when i try to access the data at a specific position in the json array it gives undefined value , it is not giving the model value.I have checked everything like json format , naming conventions with respect to my serializer but cant able to find what is going wrong , can anyone help me with solving this ?
Application adapter :
import RESTAdapter from '#ember-data/adapter/rest';
export default class ApplicationAdapter extends RESTAdapter {
buildURL(...args) {
return "http://localhost:8082/ContactManagementSystem1/api/contact/5";
}
headers = {
'Accept': '*/*',
};
}
Json response from api :
[
{
"firstName": "Example",
"lastName": "K",
"deletedAt": "",
"mobileNumberHome": "7827382738",
"companyName": "Example",
"dateOfBirth": "2000-04-12",
"id": 21,
"userId": 4,
"mobileNumberWork": "2738273788",
"email": "rath#gmail.com"
},
{
"firstName": "nameexample2",
"lastName": "p",
"deletedAt": "",
"mobileNumberHome": "8989898996",
"companyName": "Business ",
"imageURL": "actress1.jfif",
"dateOfBirth": "2021-10-05",
"id": 51,
"userId": 4,
"mobileNumberWork": "8667889896",
"email": "nameexample2h#gmail.com"
}
]
Serializer :
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeResponse(store, primaryModelClass,payload,id,requestType){
arguments[2] = {
"contacts" : payload
}
return this._super(...arguments);
}
});
Since my json response is different from the RestSerializer format i have written some code in the serializer for normalising the response.
Route where i fetch data using store.findAll()
import Route from '#ember/routing/route';
import {inject as Service } from '#ember/service';
export default class UserContactRoute extends Route {
#Service store;
async model() {
return this.store.findAll('contact');
}
}
These are codes which i have used , i have also checked in the inspect's console no error is been thrown , the problem is model array object were undefined.
One should use the objectAt(index) for accessing array elements because those arrays are not regular JS ones. See here:
It's important to note that RecordArray is not a JavaScript array,
it's an object that implements MutableArray. This is important
because, for example, if you want to retrieve records by index, the []
notation will not work--you'll have to use objectAt(index) instead.

Using a local Open API Standard file to to create an ARM template for a web service

I am working on an old web service where I generate the rest endpoints documentation that comply with OAS standards using a custom tool. Using this OAS json file I can deploy the API to Azure API Managements services through the portal and it all works fine. However, I need to automate this process and hence need to use ARM templates to deploy all web services to Azure APIM. I have been looking into the examples provided https://learn.microsoft.com/en-us/azure/templates/microsoft.apimanagement/service/apis but just can't seem to wrap my head around how to use a local OAS.json file or a file in github.
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Location for all resources."
}
}
},
"variables": {
"apiManagementServiceName": "price-capture"
},
"resources": [
{
"apiVersion": "2018-01-01",
"type": "Microsoft.ApiManagement/service/apis",
"name": "[variables('apiManagementServiceName')]",
"properties": {
"displayName": "Service display Name",
"apiRevision": "1",
"description": "API description",
//need help since it's not a swagger url
//wondering if there is a way to ref a local file like the option
//provided in the portal when we register api's manually.
"serviceUrl": "----",
"path": "----",
"protocols": [
"https"
],
"isCurrent": true,
"apiVersion": "v1",
"apiVersionDescription": "apiVersionDescription"
}
}
]
}
You can deploy and configure an entire API on API Management via ARM templates, but you cannot use a local file to provide the OpenApi/Swagger.
In your case the OpenApi/Swagger needs to be publicly accessible so the resource manager can read from it, so if the Github URL is freely accessible it should work.
I typically store the OpenApi/Swagger to a storage account and use the SAS token to access it from the ARM template.
You can check out this blog for details on automating API deployment in APIM:
https://blog.eldert.net/api-management-ci-cd-using-arm-templates-linked-template/
You can deploy the API using an Azure Resource Manager template of type Microsoft.ApiManagement/service/apis, and to use an Open API / swagger definition you need to specify the contentValue and and contentFormat parameters of the template
{
"name": "awesome-api-management/petstore",
"type": "Microsoft.ApiManagement/service/apis",
"apiVersion": "2018-06-01-preview",
"properties": {
"path": "petstore"
"contentValue": "petstore swagger file contents here", // or it's URL
"contentFormat": "swagger-json", // or swagger-link-json if externally available
}
}
I don't think it's possible to deploy the APIs configs via templates.
I've been trying to figure this out myself but I'm pretty sure you can't include the actual APIs you want in the service.
From what I can tell, you can't do that with the GIT repo either because that needs authentication that is manually created in the portal
I think the only thing you can automate with the ARM template is the actual API Management service and then you need to use the Azure API to add and configure the APIs on it.
However, I have yet to figure out how to do that myself.
I actually have a service ticket open to get help on that.
The API has changed slightly so this works:
The yaml file (calculatorApiFile) needs to be uploaded first to a blob storage, but this can be done as part of the deployment pipeline
{
"type": "Microsoft.ApiManagement/service/apis",
"apiVersion": "2019-01-01",
"name": "[concat(parameters('service_name'), '/b12b1d5ab8204cg6b695e3e861fdd709')]",
"dependsOn": [
"[resourceId('Microsoft.ApiManagement/service', parameters('service_name'))]"
],
"properties": {
"displayName": "Calculator",
"apiRevision": "1",
"description": "A simple Calculator ",
"path": "calc",
"value": "[concat(parameters('containerUri'), parameters('calculatorApiFile'), parameters('containerSasToken'))]",
"format": "openapi-link",
"protocols": [
"https"
],
"isCurrent": true
}
}
I figured out the answer ..all I had to do was write an azure function that fetches the oas.yaml file from a private github repository.
"variables":{
"swagger_json":"[concat(parameters('url_of_azurefunctionwithaccesskey'),'&&githuburi='parameter('raw_url'),'&githubaccesstoken=',parameter('personalaccesstoken')]"
},
"resources": [
{
"type": "Microsoft.ApiManagement/service/apis",
"name": "[concat(parameters('apimName') ,'/' ,parameters('serviceName'))]",
"apiVersion": "2018-06-01-preview",
"properties": {
"apiRevision": "[parameters('apiRevision')]",
"path": "pricecapture",
"contentValue": "[variables('swagger_json')]",
"contentFormat": "openapi-link"
}
}]
The Azure function that I had to write was something like this:
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.IO;
using System.Text;
public static async Task<HttpResponseMessage> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var gitHubUri = req.Query["githuburi"];
var gitHubAccessToken = req.Query["githubaccesstoken"];
var encoding = Encoding.ASCII;
if (string.IsNullOrEmpty(gitHubUri))
{
var errorcontent = new StringContent("please pass the raw file content URI (raw.githubusercontent.com) in the request URI string", Encoding.ASCII);
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.BadRequest,
Content = errorcontent
};
}
else if (string.IsNullOrEmpty(gitHubAccessToken))
{
var errorcontent = new StringContent("please pass the GitHub personal access token in the request URI string", Encoding.ASCII);
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.BadRequest,
Content = errorcontent
};
}
else
{
var strAuthHeader = "token " + gitHubAccessToken;
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3.raw");
client.DefaultRequestHeaders.Add("Authorization", strAuthHeader);
var response = await client.GetAsync(gitHubUri);
return response;
}
}
If you load your YAML into a variable, that can be passed to the ARM template and be passed as the value:
deploy.bat:
SETLOCAL EnableDelayedExpansion
set API_DEPLOYMENT=<deployment name>
set API_GROUP=<deployment group>
set API=<api file path.yml>
set OPENAPI=
for /f "delims=" %%x in ('type %API%') do set "OPENAPI=!OPENAPI!%%x\n"
call az deployment group create -n %API_DEPLOYMENT% -g %API_GROUP% --mode Complete -f deploy.json -p openApi="!OPENAPI!"
ENDLOCAL
deploy.json (note the use of replace)
...
{
"type": "Microsoft.ApiManagement/service/apis",
"apiVersion": "2020-12-01",
"name": "[variables('apiName')]",
"properties": {
"path": "[variables('service')]",
"apiType": "http",
"displayName": "[variables('apiDisplayName')]",
"format": "openapi",
"value": "[replace(parameters('openApi'), '\\n', '\n')]"
},
...
},
...

How to define a variable within a JSON file and use it within JSON file

I'm trying to find if JSON file supports defining variables and using them within that JSON file?
{
"artifactory_repo": "toplevel_virtual_NonSnapshot",
"definedVariable1": "INSTANCE1",
"passedVariable2": "${passedFromOutside}",
"products": [
{ "name": "product_${definedVariable1}_common",
"version": "1.1.0"
},
{ "name": "product_{{passedVariable2}}_common",
"version": 1.5.1
}
]
}
I know YAML files allow this but now sure if JSON file allows this behavior or not. My plan is that a user will pass "definedVariable" value from Jenkins and I'll create a target JSON file (after substi
This might help you:
{
"artifactory_repo": "toplevel_virtual_NonSnapshot",
"definedVariable1": "INSTANCE1",
"passedVariable2": `${passedFromOutside}`,
"products": [
{ "name": `product_${definedVariable1}_common`,
"version": "1.1.0"
},
{ "name": `product_${passedVariable2}_common`,
"version": 1.5.1
}
]
}
*Note the use of `` instead of ''

Failed to trigger translation for DWF files to STEP

I’m trying to translate my .DWF file to STEP using the Model Derivative API:
{
"input": {
"urn":"<<DWF URN HERE>>"
},
"output": {
"destination": {
"region": "us"
},
"formats": [
{
"type": "step"
}]
}
}
But the request fails with this reply:
{
"diagnostic": "Failed to trigger translation for this file."
}
Am I missing anything here?
STEP export format is currently not available for DWF files :(
Here you can find a list of all the design file formats and the export file format supported for them:
https://developer.autodesk.com/en/docs/model-derivative/v2/overview/supported-translations/
You can also access this information programmatically from here:
https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/formats-GET/
Cheers,
Adam