Collection+JSON with AngularJS - json

I'm working on a project where various tables of data will be displayed with AngularJS. The data will be in the Collection+JSON format, as shown below. I found this library https://github.com/Medycation/angular-collection-json, I'm not sure how to make it work. Below is an example of the data.
angular.module('app', ['cj']);
var $injector = angular.injector();
var cj = $injector.get('cj');
cj("cjapi1.php").then(function(cjProvider){
console.log(collection.items());
});
I tried the above. In the console it says I need to register cjProvider as a provider. Any help with how to set this up properly would be appreciated. Thanks.
{
“collection”:
{
“version”: “0.1”,
“href” : “https://example.com/companies”
“items” : [
{
“href” : “https://example.com/companies/123”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 1”}
}
},
{
“href” : “https://example.com/companies/1234”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 2”}
}
},
]
}

Please configure your cjProvider while configuring your module. Check the below code template for the reference to configure cjProvider.
angular.module('app', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});
Please make sure that you have configured your transformUrl just shown above.
Your base url must be configured in cjProvider and while hitting any url ang getting data you should transform your request like here you are requesting cjapi1.php. so your baseurl must be append before that like your_base_url + 'cjapi1.php' this will be done for all requesting api. So cjProvider will take care that and will return api path and in .then(responce) you will get your responce which is collection.
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});

Are you trying to configure or get the contents of the collection from php call?
Looks like a typo to me but try this to get collection:
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});
...and this for configuration of your provider:
angular.module('agile', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});

Related

Sending multiple files in Postman - NodeJS

I have a JSON request in the following structure-
{
"user_id" : "1",
"user_details" : {
"name" : "my_name"
"passport_image" : "passport_image.jpg"
},
"user_documents" : [
{"file" : "doc_1.jpg"},
{"file" : "doc_2.jpg"}
]
}
How can I send files via postman that are part of a JSON request?
This is what I tried -
But then passport_image.jpg would be its own field and not part of user_details object, correct?
And what about the array of file objects under user_documents? How can I send it too in the request?
I would appreciate help as I'm quite new to using form-data requests rather than raw JSON ones.
You can set the keys as array. It can be set like this. user_documents[0] and the respective file for it.
This will work!
The above answer is wrong, the way to do it is to select the key value = to the value you used in your code, for instance see below:
const storage = multer.diskStorage({
destination: function(req,file,cb) {
cb(null,'uploads/')
},
filename: function(res,file,cb) {
console.log('file= ',file)
const uniqueSuffix=Date.now()+'-'+Math.round(Math.random()*1e9)
cb(null, file.fieldname+'-'+uniqueSuffix+'.jpg')
}
})
const upload = multer({storage:storage})
app.post('/uploads', upload.array('files',12), (req,res)=>
{
req.files.map((file)=>{
console.log('received request: ', file)
})
res.status(200).send('received files')
})
Then in postman you just select several files, in this case less than 12 after clicking on the select files button. Just one entrance for multiple files.
Actually I find solution on Youtube. You can choose multiple files by keeping Ctrl and choose multiple files.

Swagger run locally but not on IIS, not resolving base path

I am setting up Swagger for documenting my API.
I have set up the SwaggerEndpoint with a relative path the the specification json, like you see below:
When I debug locally, everything resolves fine. But my site just runs as http://localhost:44348/index.html.
When I deploy to IIS, which is on a virtual path, it blows apart:
Note that the URL in the browser has /imaging4castapi_UAT/ as part of the path
Note that the actual request for the swagger.json is missing that base part of the path.
Here's what I've tried:
I tried removing the RoutePrefix override. But that doesn't resolve.
I tried using an application path like "~/swagger/..." but that's translated by the server on view elements like Razor pages and css and doesn't work here in Startup.
I'm struggling to understand if this is a client setup issue or something related to how my site is hosted on IIS.
Thoughts?
Try using a relative path:
setupAction.SwaggerEndpoint("../swagger/Imaging4CastApiSpecification/swagger.json", "4Cast API");
Please note answer and explanation from the following issue: SwashBuckle
Here is my Swagger config for once of PRD application. Hope it helps
public static IServiceCollection AddSwaggerConfig(this IServiceCollection services, IHostingEnvironment env,
string title, string version)
=> services.AddSwaggerGen(c =>
{
//Ensure XML Document File of project is checked for both Debug and Release mode
c.IncludeXmlComments("Your App.xml");
//Display Enum name
c.DescribeAllEnumsAsStrings();
//c.OperationFilter<AddRequiredHeaderParameter>();
//Authentication for Bearer
c.AddSecurityDefinition("Bearer",
new ApiKeyScheme
{
In = "header",
Description = "Please enter JWT with Bearer into field",
Name = "Authorization",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{"Bearer", Enumerable.Empty<string>()}
});
c.SwaggerDoc(version, new Info
{
Title = title,
Version = version,
Description = "",
Contact = new Contact
{
Email = "Support#ABC.com",
Name = ""
}
});
});
Startup file
app.
//Swagger
.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"./{_version}/swagger.json", Title);
});
The version is app variable from Config file which will be filtered by CI/CD
Swagger does not support Virtual Directory by default. Try and add this to your Startup.cs
app.UseSwagger(c =>
{
c.RouteTemplate = "virtual_path/{documentName}/swagger.json";
});
app.UseSwaggerUI(c =>
{
//Include virtual directory
c.RoutePrefix = "virtual_path";// add your virtual path here.
c.SwaggerEndpoint("v1/swagger.json", "Api v1");
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"./v1/swagger.json", "Api v1");
});
My fix was following Killnines last comment to remove the preceding forward slash so that it looks like the following;
app.UseSwagger();
app.UseSwaggerUI(options => {
options.SwaggerEndpoint("swagger/v1/swagger.json", "Your API v1");
});

response with status 200: ok

I am trying to figure out how to plot data from a local '.JSON' file using angular2-highcharts example.
I followed the example in 'https://www.npmjs.com/package/angular2-highcharts' to first understand how to plot .JSON data and it worked. I took the data available for the example and created a local .JSON file (copied the content from 'https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK' in notepad and saved it with UTF-8 encoding as a .JSON file), and replaced the file path for the JSON request to this. When I do this though, I get an error - response with status 200.
constructor(jsonp : Jsonp) {
//jsonp.get('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK').subscribe(res => {
jsonp.get('./data.json').subscribe(res => {
this.options = {
title : { text : 'AAPL Stock Price' },
series : [{
name : 'AAPL',
data : res.json(),
tooltip: {
valueDecimals: 2
}
}]
};
});
}
options: Object;
};
Since I am not super familiar with json data/ Javascript or angular2 I am not sure if I am missing something very basic here. Any help is appreciated.
as far as I know, Response Status 200 specifies that request was successful. i.e. your request was successfully handled. perhaps you want to try checking response data.
check your callback for response data.
Using http instead of json helped. I made use of the suggestion in this answer https://stackoverflow.com/a/36305814/4567096.

Papa Parse reading CSV locally

Can someone point to or show me a working example of Papa Parse reading a csv file.
When I try to use :
Papa.parse(file, {
complete: function(results) {
console.log("Finished:", results.data);
}
});
the file name is returned in the array instead of the data within. None of the internet examples actually work. The official demo works correctl inspecting its code I cant find it making use of the above strangely.
As #Matt mentioned in his comment, the trick is not to pass a file name, but a file object. This also was not intuitive to me at first, so here is a quick solution:
var data;
function parse() {
var file = document.getElementById('myDOMElementId').files[0];
Papa.parse(file, {
header: true,
dynamicTyping: true,
complete: function(results) {
console.log("Finished:", results.data);
data = results.data;
}
});
}
Note that you have to call the results in this way when working with a local file. If you want to work with the results elsewhere, assign it to a global variable.
I have faced the same problem and it was solved by 2 actions:
1- Adding a callback function
2- connecting to a local oython server/changing browser's security settigns
Check this:
https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally
I did not pass an object but a string with the file name/path and it worked for me.

Angular resource 404 Not Found

I've read other posts that have similar 404 errors, my problem is that I can correctly query the JSON data, but can't save without getting this error.
I'm using Angular's $resource to interact with a JSON endpoint. I have the resource object returning from a factory as follows:
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' });
});
My JSON is valid and I can successfully use resource's query() method to return the objects inside of my directive, like this:
var item = Product.query().$promise.then(function(promise) {
console.log(promise) // successfully returns JSON objects
});
However, when I try to save an item that I've updated, using the save() method, I get a 404 Not Found error.
This is the error that I get:
http://localhost:3000/api/products.json/12-34 404 (Not Found)
I know that my file path is correct, because I can return the items to update the view. Why am I getting this error and how can I save an item?
Here is my data structure:
[
{
"id": "12-34",
"name": "Greece",
"path": "/images/athens.png",
"description": ""
},
...
]
By default the $save method use the POST verb, you will need to figure out which HTTP verbs are accepted by your server en order to make an update, most modern api servers accept PATCH or PUT requests for updating data rather than POST.
Then configure your $resource instance to use the proper verb like this :
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' }, {'update': { method:'PUT' }});
});
check $resource docs for more info.
NOTE: $resource is meant to connect a frontend with a backend server supporting RESTful protocol, unless you are using one to receive data & save it into a file rather than a db.
Otherwise if you are only working with frontend solution where you need to implement $resource and have no server for the moment, then use a fake one, there is many great solutions out there like deployd.
You probably don't implement POST method for urls like /api/products.json/12-34. POST method is requested from angular for saving a new resource. So you need to update your server side application to support it and do the actual saving.
app.factory('Product', function($resource) {
return $resource('api/products.json/:id', { id: '#id' });
});
Try adding "/:id" at the end of the URL string.