Calling self-serv API flight offers price get error "38196 resource not found" - amadeus

I called the flight offer search API. It returned 8 flight offers. I then picked the first offer and called the flight offer price API. I got this error
{ "errors": [ { "code": 38196, "title": "Resource not found", "detail": "The targeted resource doesn't exist", "status": 404 } ] }
Can anyone let me know what is wrong with my code please? Thanks in advance.
confirmFlightOffer = #"{
""data"": {
""type"": ""flight-offers-pricing"",
""flightOffers"": [
{
""type"": ""flight-offer"",
""id"": ""1"",
""source"": ""GDS"",
""instantTicketingRequired"": false,
""nonHomogeneous"": false,
""oneWay"": false,
""lastTicketingDate"": ""2020-06-06"",
""numberOfBookableSeats"": 9,
""itineraries"": [
{
""duration"": ""PT1H35M"",
""segments"": [
{
""departure"": {
""iataCode"": ""SYD"",
""terminal"": ""2"",
""at"": ""2020-06-14T13:20:00""
},
""arrival"": {
""iataCode"": ""MEL"",
""terminal"": ""4"",
""at"": ""2020-06-14T14:55:00""
},
""carrierCode"": ""JQ"",
""number"": ""513"",
""aircraft"": { ""code"": ""320"" },
""operating"": { ""carrierCode"": ""JQ"" },
""duration"": ""PT1H35M"",
""id"": ""22"",
""numberOfStops"": 0,
""blacklistedInEU"": false
}
]
}
],
""price"": {
""currency"": ""AUD"",
""total"": ""140.74"",
""base"": ""102.75"",
""fees"": [
{
""amount"": ""0.00"",
""type"": ""SUPPLIER""
},
{
""amount"": ""0.00"",
""type"": ""TICKETING""
}
],
""grandTotal"": ""140.74""
},
""pricingOptions"": {
""fareType"": [ ""PUBLISHED"" ],
""includedCheckedBagsOnly"": true
},
""validatingAirlineCodes"": [ ""HR"" ],
""travelerPricings"": [
{
""travelerId"": ""1"",
""fareOption"": ""STANDARD"",
""travelerType"": ""ADULT"",
""price"": {
""currency"": ""AUD"",
""total"": ""140.74"",
""base"": ""102.75""
},
""fareDetailsBySegment"": [
{
""segmentId"": ""22"",
""cabin"": ""ECONOMY"",
""fareBasis"": ""HLOW"",
""class"": ""H"",
""includedCheckedBags"": {
""weight"": 20,
""weightUnit"": ""KG""
}
}
]
}
]
}
]
}
}";
var client = new RestClient(_apiUrl);
client.Timeout = -1;
var request = new RestRequest("​/v1/shopping/flight-offers/pricing", Method.POST);
request.AddHeader("Authorization", $"Bearer {_token}");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", confirmFlightOffer, ParameterType.RequestBody);
var response = client.Execute<ConfirmFlightOfferResponse>(request);

I found the problem
This works
var client = new RestClient(_apiUrl + "/v1/shopping/flight-offers/pricing");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
but this doesn't
var client = new RestClient(_apiUrl);
client.Timeout = -1;
var request = new RestRequest("/v1/shopping/flight-offers/pricing",Method.POST);
Don't know why.

Related

In SendEmail MSGRAPH API InternalServerError,Object reference not set to an instance of an object

Tried to use Microsoft Graph Email API, BUT getting following error.
ODATA Payload
"message": {
"subject": "Send email",
"body": {
"contentType": "text",
"content": "wuirbmndf"
},
"toRecipients": [
{
"emailAddress": {
"address": "emailid"
}
}
],
"attachments": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"name": "attachment.txt",
"contentType": "text/plain",
"contentBytes": "SGVsbG8gV29ybGQh"
}
],
"from": {
"emailAddress": {
"address": "sender email id"
}
}
}
My Code Looks Like ->
client.BaseUrl = new Uri(String.Format("https://graph.microsoft.com/v1.0/me/sendmail"));
RestRequest request = new RestRequest();
request.Method = Method.POST;
request.AddParameter("Authorization", string.Format("Bearer " + emailObj.AccessToken), ParameterType.HttpHeader);
request.AddParameter("application/json", json, ParameterType.RequestBody);
//request.AddHeader("ContentType", "application/json");
//request.JsonSerializer.ContentType = "string";
var result = client.Execute(request);
And I am Getting InternalServerError with error Object reference not set to an instance of an object.
{
"error": {
"code": "InternalServerError",
"message": "Object reference not set to an instance of an object.",
"innerError": {
"request-id": "22ec4d88-2140-497f-bf28-80c83d7aa6a9",
"date": "2020-05-27T04:24:14"
}
}
}
thanks in advance.

Convert File in MS Graph API on SPFx return undefined

When i try to download a file from API Graph accesing to Drive or Sites with javascript on SPFx this return undefined.
my webpart code:
import { Version } from '#microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '#microsoft/sp-webpart-base';
import * as strings from 'Docx2PdfWebPartStrings';
import { MSGraphClient } from '#microsoft/sp-http';
export interface IDocx2PdfWebPartProps {
description: string;
}
export default class Docx2PdfWebPart extends BaseClientSideWebPart<IDocx2PdfWebPartProps> {
public async render(): Promise<void> {
const client: MSGraphClient = await this.context.msGraphClientFactory.getClient();
var tenant = 'test';
var siteID = `${tenant}.sharepoint.com,12adb250-26f4-4dbb-9545-71d029bad763,8fdc3f56-2d6d-42d9-9a4d-d684e73c341e`;
var fileID = '01MBNFB7EIQLARTATNE5G3XDJNYBD2A3IL';
var fileName = 'Test.docx';
//This work
var site = await client.api(`/sites/${tenant}.sharepoint.com:/sites/dev:/drive?$select=id,weburl`).get();
console.log(site);
try {
//This not work
var fileFromDrive = await client.api(`/drive/root:/${fileName}:/content?format=pdf`).get();
console.log(fileFromDrive);
var fileFromSite = await client.api(`/sites/${siteID}/drive/items/${fileID}/content?format=pdf`).get();
console.log(fileFromSite);
} catch (error) {
console.log(error);
}
this.domElement.innerHTML = `<h1>Hola Mundo</h1>`;
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}
The chrome console log
But when i use Graph Explorer it works correctly
This is my package-solution.json
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "docx-2-pdf-client-side-solution",
"id": "f4b5db4f-d9ff-463e-b62e-0cc9c9e94089",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "Sites.Read.All"
},
{
"resource": "Microsoft Graph",
"scope": "Files.Read.All"
},
{
"resource": "Microsoft Graph",
"scope": "Files.ReadWrite.All"
},
{
"resource": "Microsoft Graph",
"scope": "Sites.ReadWrite.All"
}
]
},
"paths": {
"zippedPackage": "solution/docx-2-pdf.sppkg"
}
}
I use the following articles
https://learn.microsoft.com/en-us/graph/api/driveitem-get-content?view=graph-rest-1.0&tabs=javascript
https://learn.microsoft.com/en-us/graph/api/driveitem-get-content-format?view=graph-rest-1.0&tabs=javascript#code-try-1
Try using the callback property instead of await:
client.api(`/drive/root:/${fileName}:/content?format=pdf`).get((err, response) => console.log("your response:", err, response));

"Requested device not found" when using chrome.tabCapture.capture

Problem
I want to capture the audio output of a tab automatically. I'm currently thinking of doing this using Puppeteer (headful), by loading an extension that uses chrome.tabCapture.capture. From my Puppeteer script, I evaluate code within the extensions background.js to get the tab capture started. However, chrome.runtime.lastError.message is set to Requested device not found.
The extension works as expected outside of Puppeteer and in a Chrome browser.
Any idea why I'm getting Requested device not found?
What does the extension's background.js look like?
function startRecording() {
chrome.tabCapture.capture(options, stream => {
if (stream === null) {
console.log(`Last Error: ${chrome.runtime.lastError.message}`);
return;
}
try {
const recorder = new MediaRecorder(stream);
} catch (err) {
console.log(err.message);
}
recorder.addEventListener('dataavailable', event => {
const { data: blob, timecode } = event;
console.log(`${timecode}: ${blob}`);
});
const timeslice = 60 * 1000;
recorder.start(timeslice);
});
}
What does the relevant part of your Puppeteer script look like?
...
const targets = await browser.targets();
const backgroundPageTarget = targets.find(target => target.type() === 'background_page' && target.url().startsWith('chrome-extension://abcde/'));
const backgroundPage = await backgroundPageTarget.page();
const test = await backgroundPage.evaluate(() => {
startRecording();
return Promise.resolve(42);
});
...
Extension Manifest:
{
"name": "Test",
"description": "",
"version": "1.0",
"icons": {
"128": "icon.png"
},
"manifest_version": 2,
"browser_action": {
"default_popup": "test.html"
},
"background": {
"scripts": [
"background.js"
],
"persistent": true
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"all_frames": false,
"js": [
"contentScript.js"
]
}
],
"permissions": [
"activeTab",
"tabs",
"tabCapture",
"storage"
]
}

Unable to use IdentityManager API from Postman

I am using postman and I am trying to get the users list from identity Manager. But I am unable to configure the app correctly. I try to get the users from https://localhost/idm/api/users
I get the token with the API+idmgr+openid scopes and I have the Administrator role in my claims.
Here is the startup file:
namespace WebHost
{
internal class Startup
{
public void Configuration(IAppBuilder app)
{
LogProvider.SetCurrentLogProvider(new NLogLogProvider());
string connectionString = ConfigurationManager.AppSettings["MembershipRebootConnection"];
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
Authority = "https://localhost/ids",
ClientId = "postman",
RedirectUri = "https://localhost",
ResponseType = "id_token",
UseTokenLifetime = false,
Scope = "openid idmgr",
SignInAsAuthenticationType = "Jwt",
Notifications = new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = n =>
{
n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
return Task.FromResult(0);
}
}
});
X509Certificate2 cert = Certificate.Get();
app.Map("/idm", adminApp =>
{
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AllowedAudiences = new string[] { "https://localhost/ids" + "/resources" },
AuthenticationType = "Jwt",
IssuerSecurityTokenProviders = new[] {
new X509CertificateSecurityTokenProvider("https://localhost/ids", cert)
},
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
});
var factory = new IdentityManagerServiceFactory();
factory.Configure(connectionString);
var securityConfig = new ExternalBearerTokenConfiguration
{
Audience = "https://localhost/ids" + "/resources",
BearerAuthenticationType = "Jwt",
Issuer = "https://localhost/ids",
SigningCert = cert,
Scope = "openid idmgr",
RequireSsl = true,
};
adminApp.UseIdentityManager(new IdentityManagerOptions()
{
Factory = factory,
SecurityConfiguration = securityConfig
});
});
app.Map(ConfigurationManager.AppSettings["IdentityServerSuffix"], core =>
{
IdentityServerServiceFactory idSvrFactory = Factory.Configure();
idSvrFactory.ConfigureCustomUserService(connectionString);
var options = new IdentityServerOptions
{
SiteName = "Login",
SigningCertificate = Certificate.Get(),
Factory = idSvrFactory,
EnableWelcomePage = true,
RequireSsl = true
};
core.UseIdentityServer(options);
});
}
}
}
What Am I missing?
For those who may want to know how I did it, well I made a lot of search about Owin stuff and how Identity Server works and find out my problem was not that far.
I removed the JwtSecurityTokenHandler.InboundClaimTypeMap
I removed the UseOpenId stuff (don't remove it if you are using an openId external login provider (if you are using google, facebook or twitter, there is classes for that, just install the nuget, it's pretty straight forward)
This section let you configure the bearer token which is the default type token i used in my app(I decided to use password authentication to simplify Postman request to do automatic testing but I still user Code authentication in my apps)
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = ConfigurationManager.AppSettings["AuthorityUrl"],
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { ConfigurationManager.AppSettings["ApiScope"] }
});
I have disabled the IdentityManagerUi interface as I was planning to use the API
app.Map(ConfigurationManager.AppSettings["IdentityManagerSuffix"].ToString(), idmm =>
{
var factory = new IdentityManagerServiceFactory();
factory.Configure(connectionString);
idmm.UseIdentityManager(new IdentityManagerOptions()
{
DisableUserInterface = true,
Factory = factory,
SecurityConfiguration = new HostSecurityConfiguration()
{
HostAuthenticationType = Constants.BearerAuthenticationType
}
});
});
And I configure the Identity Server like this:
app.Map(ConfigurationManager.AppSettings["IdentityServerSuffix"], core =>
{
IdentityServerServiceFactory idSvrFactory = Factory.Configure();
idSvrFactory.ConfigureCustomUserService(connectionString);
var options = new IdentityServerOptions
{
SiteName = ConfigurationManager.AppSettings["SiteName"],
SigningCertificate = Certificate.Get(),
Factory = idSvrFactory,
EnableWelcomePage = true,
RequireSsl = true,
};
core.UseIdentityServer(options);
});
In IdentityServerServiceFactory I call this chunk of code:
var clientStore = new InMemoryClientStore(Clients.Get());
And the code for the Client should be something like:
public static Client Get()
{
return new Client
{
ClientName = "PostMan Application",
ClientId = "postman",
ClientSecrets = new List<Secret> {
new Secret("ClientSecret".Sha256())
},
Claims = new List<Claim>
{
new Claim("name", "Identity Manager API"),
new Claim("role", IdentityManager.Constants.AdminRoleName),
},
**Flow = Flows.ResourceOwner**, //Password authentication
PrefixClientClaims = false,
AccessTokenType = AccessTokenType.Jwt,
ClientUri = "https://www.getpostman.com/",
RedirectUris = new List<string>
{
"https://www.getpostman.com/oauth2/callback",
//aproulx - 2015-11-24 -ADDED This line, url has changed on the postman side
"https://app.getpostman.com/oauth2/callback"
},
//IdentityProviderRestrictions = new List<string>(){Constants.PrimaryAuthenticationType},
AllowedScopes = new List<string>()
{
"postman",
"IdentityManager",
ConfigurationManager.AppSettings["ApiScope"],
Constants.StandardScopes.OpenId,
IdentityManager.Constants.IdMgrScope,
}
};
}
On the postman side just do:
POST /ids/connect/token HTTP/1.1
Host: local-login.net
Cache-Control: no-cache
Postman-Token: 33e98423-701f-c615-8b7a-66814968ba1a
Content-Type: application/x-www-form-urlencoded
client_id=postman&client_secret=SecretPassword&grant_type=password&scope=APISTUFF&username=apiViewer&password=ICanUseTheApi
Hope that it will help somebody
Shaer,
I saw your comment and because of that I've created a project (make sure you clone the postmanexample branch) where you can see a working example related to Alegrowin's post. The idea is use postman to access the IdentityManager Api.
Steps
Open postman and choose the POST verb
Put this as url: https://localhost:44337/ids/connect/token
In header put key = Content-Type and value = application/x-www-form-urlencoded
In the body, choose raw and paste this client_id=postman&client_secret=ClientSecret&grant_type=password&scope=idmgr&username=admin&password=admin
Hit send
After this you are going to receive something like this
{"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJwb3N0bWFuIiwic2NvcGUiOiJpZG1nciIsInN1YiI6Ijk1MWE5NjVmLTFmODQtNDM2MC05MGU0LTNmNmRlYWM3YjliYyIsImFtciI6WyJwYXNzd29yZCJdLCJhdXRoX3RpbWUiOjE1MDU1ODg1MTgsImlkcCI6Imlkc3J2IiwibmFtZSI6IkFkbWluIiwicm9sZSI6IklkZW50aXR5TWFuYWdlckFkbWluaXN0cmF0b3IiLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMiLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMvcmVzb3VyY2VzIiwiZXhwIjoxNTA1NTkyMTE4LCJuYmYiOjE1MDU1ODg1MTh9.h0KjlnKy3Ml-SnZg6cYSPJW4XxsOFxDB8K9JY4Zx_I1KbMQxctjkDrTVfSylfjFXlwpyBD-qqfxmRkOKsz_6zSZneaJpyWsJt2FTqCNOWJJV9BdPbViWcM_vADFkVpwiiSaTCv7k08xwj8StGCq5zlYLU68k8awYpXzgpz0O8zPZpfc0oSN3ZQJVFEKBfE4ATbPo6ut2i0_Y3lPbQiwjXJgA_wwp-W0L3zY8A5rfYSwKU0KzS51BKBSn6svBCjTu84Dm2KM-zlManMar1Ybjoy108Xvuliq_zBNdbeEt-Daau_RNrasw1tya_cZicK85IB1TJdUSKPGwNG5xEirNzg",
"expires_in": 3600,
"token_type": "Bearer"}
Copy the access token and create a GET request
Put this as url: https://localhost:44337/idm/api/users?count=10&start=0
Into the headers put key = Authorization and value = Bearer [paste the token]
Example
Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJwb3N0bWFuIiwic2NvcGUiOiJpZG1nciIsInN1YiI6Ijk1MWE5NjVmLTFmODQtNDM2MC05MGU0LTNmNmRlYWM3YjliYyIsImFtciI6WyJwYXNzd29yZCJdLCJhdXRoX3RpbWUiOjE1MDU1ODg1MTgsImlkcCI6Imlkc3J2IiwibmFtZSI6IkFkbWluIiwicm9sZSI6IklkZW50aXR5TWFuYWdlckFkbWluaXN0cmF0b3IiLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMiLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzNy9pZHMvcmVzb3VyY2VzIiwiZXhwIjoxNTA1NTkyMTE4LCJuYmYiOjE1MDU1ODg1MTh9.h0KjlnKy3Ml-SnZg6cYSPJW4XxsOFxDB8K9JY4Zx_I1KbMQxctjkDrTVfSylfjFXlwpyBD-qqfxmRkOKsz_6zSZneaJpyWsJt2FTqCNOWJJV9BdPbViWcM_vADFkVpwiiSaTCv7k08xwj8StGCq5zlYLU68k8awYpXzgpz0O8zPZpfc0oSN3ZQJVFEKBfE4ATbPo6ut2i0_Y3lPbQiwjXJgA_wwp-W0L3zY8A5rfYSwKU0KzS51BKBSn6svBCjTu84Dm2KM-zlManMar1Ybjoy108Xvuliq_zBNdbeEt-Daau_RNrasw1tya_cZicK85IB1TJdUSKPGwNG5xEirNzg
Hit send
You should receive something like this
{
"data": {
"items": [
{
"data": {
"subject": "081d965f-1f84-4360-90e4-8f6deac7b9bc",
"username": "alice",
"name": "Alice Smith"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/081d965f-1f84-4360-90e4-8f6deac7b9bc",
"delete": "https://localhost:44337/idm/api/users/081d965f-1f84-4360-90e4-8f6deac7b9bc"
}
},
{
"data": {
"subject": "5f292677-d3d2-4bf9-a6f8-e982d08e1306",
"username": "bob",
"name": "Bob Smith"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/5f292677-d3d2-4bf9-a6f8-e982d08e1306",
"delete": "https://localhost:44337/idm/api/users/5f292677-d3d2-4bf9-a6f8-e982d08e1306"
}
},
{
"data": {
"subject": "e3c7fd2b-3942-456f-8871-62e64c351e8c",
"username": "xoetuvm",
"name": "Uylocms Xcyfhpc"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/e3c7fd2b-3942-456f-8871-62e64c351e8c",
"delete": "https://localhost:44337/idm/api/users/e3c7fd2b-3942-456f-8871-62e64c351e8c"
}
},
{
"data": {
"subject": "0777d8de-91be-41e2-82ae-01c4576c7aca",
"username": "xdbktbb",
"name": "Qbcqwrg Mypxduu"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/0777d8de-91be-41e2-82ae-01c4576c7aca",
"delete": "https://localhost:44337/idm/api/users/0777d8de-91be-41e2-82ae-01c4576c7aca"
}
},
{
"data": {
"subject": "10d2760a-2b3f-4912-af2a-2bcd9d113af9",
"username": "acrkkzf",
"name": "Qcmwcha Kdibtke"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/10d2760a-2b3f-4912-af2a-2bcd9d113af9",
"delete": "https://localhost:44337/idm/api/users/10d2760a-2b3f-4912-af2a-2bcd9d113af9"
}
},
{
"data": {
"subject": "5e16f086-a487-4429-b2a6-b05a739e1e71",
"username": "wjxfulk",
"name": "Eihevix Bjzjbwz"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/5e16f086-a487-4429-b2a6-b05a739e1e71",
"delete": "https://localhost:44337/idm/api/users/5e16f086-a487-4429-b2a6-b05a739e1e71"
}
},
{
"data": {
"subject": "256e23de-410a-461d-92cc-55684de8be6f",
"username": "zputkfb",
"name": "Vhwjjpd Stfpoum"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/256e23de-410a-461d-92cc-55684de8be6f",
"delete": "https://localhost:44337/idm/api/users/256e23de-410a-461d-92cc-55684de8be6f"
}
},
{
"data": {
"subject": "725cc088-96c3-490d-bc66-a376c8ca34ff",
"username": "teshydj",
"name": "Tirsnex Tdlkfii"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/725cc088-96c3-490d-bc66-a376c8ca34ff",
"delete": "https://localhost:44337/idm/api/users/725cc088-96c3-490d-bc66-a376c8ca34ff"
}
},
{
"data": {
"subject": "ac773092-e3db-4711-9c95-a2a57c1ff25f",
"username": "blulsuj",
"name": "Puuncng Lbmlcsb"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/ac773092-e3db-4711-9c95-a2a57c1ff25f",
"delete": "https://localhost:44337/idm/api/users/ac773092-e3db-4711-9c95-a2a57c1ff25f"
}
},
{
"data": {
"subject": "81f878b1-016e-4fea-9929-54e3b1d55cce",
"username": "yeqwlfy",
"name": "Qtfimdr Sxvgizd"
},
"links": {
"detail": "https://localhost:44337/idm/api/users/81f878b1-016e-4fea-9929-54e3b1d55cce",
"delete": "https://localhost:44337/idm/api/users/81f878b1-016e-4fea-9929-54e3b1d55cce"
}
}
],
"start": 0,
"count": 10,
"total": 18806,
"filter": null
},
"links": {
"create": {
"href": "https://localhost:44337/idm/api/users",
"meta": [
{
"type": "username",
"name": "Username",
"dataType": 0,
"required": true
},
{
"type": "password",
"name": "Password",
"dataType": 1,
"required": true
},
{
"type": "name",
"name": "Name",
"dataType": 0,
"required": true
},
{
"type": "Age",
"name": "Age",
"dataType": 4,
"required": true
},
{
"type": "IsNice",
"name": "IsNice",
"dataType": 5,
"required": true
},
{
"type": "role.admin",
"name": "Is Administrator",
"dataType": 5,
"required": true
}
]
}
}
}
Kind regards
Daniel

MEAN.JS: Filter in mongoose middleware

This is my code in backend controller in MEAN JS:
exports.list = function(req, res) {
// configure the filter using req params
var filters = {
filters : {
optional : {
contains : req.query.filter
}
}
};
var sort = {
asc : {
desc: 'name'
}
};
Province
.find()
.filter(filters)
.order(sort)
.exec(function (err, provinces) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(provinces);
}
});
};
The request:
http://localhost:3000/provinces?filter[name]=provincia de Barcelona
Returns a filtered result, as expected:
[
{
"_id": "54ba72903f51d73c4aff6da6",
"community": "54ba689f5fdfbdea292b8737",
"location": "{lat: '41.386290', lng: '2.184988', zoom: '11'}",
"__v": 0,
"name": "provincia de Barcelona"
}
]
When I use a different attribute, the filter stops working. Example:
http://localhost:3000/provinces?filters[community]=54ba69755fdfbdea292b8738
Return this:
{
"message": ""
}
And console.log(err) return this:
[CastError: Cast to ObjectId failed for value "/54ba689f5fdfbdea292b8737/i" at path "community"]
message: 'Cast to ObjectId failed for value "/54ba689f5fdfbdea292b8737/i" at path "community"',
name: 'CastError',
type: 'ObjectId',
value: /54ba689f5fdfbdea292b8737/i,
path: 'community' }
The original document:
[
{
"_id": "54ba72903f51d73c4aff6da6",
"community": "54ba689f5fdfbdea292b8737",
"location": "{lat: '41.386290', lng: '2.184988', zoom: '11'}",
"__v": 0,
"name": "provincia de Barcelona"
},
{
"_id": "54ba73c33f51d73c4aff6da7",
"community": "54ba69755fdfbdea292b8738",
"location": "{lat: '42.4298846', lng: '-8.644620199999963', zoom: '11'}",
"__v": 0,
"name": "provincia de Pontevedra"
}
]
Maybe is not the best way, but works :)
exports.list = function(req, res) {
var community = {community: ''};
community.community = mongoose.Types.ObjectId(req.query.filter.community);
console.log(community);
var filters = {
filters : {
optional : {
contains : community
}
}
};
var sort = {
asc : {
desc: 'name'
}
};
Province
.find()
.filter(filters)
.order(sort)
.exec(function (err, provinces) {
console.log(err);
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(provinces);
}
});
};
The request:
http://localhost:3000/provinces?filter[community]=54ba689f5fdfbdea292b8737
The result:
[
{
"_id": "54ba72903f51d73c4aff6da6",
"community": "54ba689f5fdfbdea292b8737",
"location": "{lat: '41.386290', lng: '2.184988', zoom: '11'}",
"__v": 0,
"name": "provincia de Barcelona"
}
]