I tried to use the named saves as below and as explained in the release notes here, but it dosen't work and returns:
Uncaught Error: The 'entities' parameter is optional or it must be an array where each element must be an entity => breeze.debug.js:724
proto.check => breeze.debug.js:724
proto.saveChanges => breeze.debug.js:11150
sendEmail
The function is:
var sendEmail = function () {
var option = new breeze.SaveOptions({ resourceName: 'sendMail'})
return manager.saveChanges({ saveOptions: option })
.then(saveSucceeded)
.fail(saveFailed);
function saveSucceeded(saveResult) {
log('La email è stata invata.', saveResult, true);
}
function saveFailed(error) {
var msg = 'Invio della email è fallito: ' + getErrorMessages(error);
logError(msg, error);
error.message = msg;
throw error;
}
};
Any help appretiated!
The writeup in the release notes has the wrong syntax. I will have it fixed.
The first arg to EntityManager.saveChanges is always a list of entities, or it can be null to indicate all entities. The 2nd arg is an optional SaveOptions instance. See here. So your expression should be
var option = new breeze.SaveOptions({ resourceName: 'sendMail'})
return manager.saveChanges(null, option)
Related
I've read the various implementations of filterPredicate on SO, Github, etc but they aren't helpful for me to understand what to do with type ahead searches.
I enter a letter into an input form field, say p, and I receive all the data with last names starting with p from the db. That part of my setup works fine. However, I don't want to hit the db again when I type the next letter, say r. I want to filter the data table for last names starting with pr. This is where the trouble starts.
When I type the second letter I have an if/else statement that tests if the var I'm using has >1 in the string. When it does I pass params to a function for the custom filtering on the table with the data already downloaded from the db. I'm avoiding a db call with every letter, which does work. I don't understand "(data, filter)". They seem like params but aren't. How do they work? What code is needed to finish this?
(I have `dataSource.filter = filterValue; working fine elsewhere.)
Params explained:
column = user_name
filterValue = pr...
The confusion:
public filterColumn(column: string, filterValue: string, dataSource) {
dataSource.filterPredicate = (data, filter) => {
console.log('data in filter column: ', data); // Never called.
// What goes here?
// return ???;
}
}
My dataSource object. I see filterPredicate, data, and filter properties to work with. Rather abstract how to use them.
dataSource in filterColumn: MatTableDataSource {_renderData: BehaviorSubject, _filter: BehaviorSubject, _internalPageChanges: Subject, _renderChangesSubscription: Subscriber, sortingDataAccessor: ƒ, …}
filterPredicate: (data, filter) => {…}arguments: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
at Function.invokeGetter (<anonymous>:2:14)]caller: (...)length: 2name: ""__proto__: ƒ ()[[FunctionLocation]]: data-utilities.service.ts:43[[Scopes]]: Scopes[3]
filteredData: (3) [{…}, {…}, {…}]
sortData: (data, sort) => {…}
sortingDataAccessor: (data, sortHeaderId) => {…}
_data: BehaviorSubject {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}
_filter: BehaviorSubject {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}
_internalPageChanges: Subject {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}
_paginator: MatPaginator {_isInitialized: true, _pendingSubscribers: null, initialized: Observable, _disabled: false, _intl: MatPaginatorIntl, …}
_renderChangesSubscription: Subscriber {closed: false, _parentOrParents: null, _subscriptions: Array(1), syncErrorValue: null, syncErrorThrown: false, …}
_renderData: BehaviorSubject {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}data: (...)filter: (...)paginator: (...)sort: (...)__proto__: DataSource
I've included most of the component I made in Angular for typeahead search. The guts of the typeahead code is in the utilities shared component at the bottom. I used a shared component here because I'll use this in many places. However, I think it is a hack and a more elegant answer is possible. This works, it is easy, but not all that pretty. I can't afford more time to figure out pretty now. I suspect the answer is in RegEx.
In the typeahead.compoent in the .pipe you'll find how I call the code in the utility.
This code is in a shared component typeahead.component.ts
public searchLastName$ = new Subject<string>(); // Binds to the html text box element.
ngAfterViewInit() {
// -------- For Column Incremental Queries --------- //
// searchLastName$ binds to the html element.
this.searchLastName$.subscribe(result => {
this.queryLastName(result);
});
}
// --------- LAST NAME INCREMENTAL QUERY --------------- //
private queryLastName(filterValue) {
// Custom filter for this function. If in ngOnInit on the calling component then it applies
// to the whole calling component. We need various filters so that doesn't work.
this.membersComponent.dataSource.filterPredicate = (data: { last_name: string }, filterValue: string) =>
data.last_name.trim().toLowerCase().indexOf(filterValue) !== -1;
// When the first letter is typed then get data from db. After that just filter the table.
if (filterValue.length === 1) {
filterValue = filterValue.trim(); // Remove whitespace
// filterValue = filterValue.toUpperCase(); // MatTableDataSource defaults to lowercase matches
const lastNameSearch = gql`
query ($last_name: String!) {
lastNameSearch(last_name: $last_name) {
...membersTableFrag
}
}
${membersTableFrag}
`;
this.apollo
.watchQuery({
query: lastNameSearch,
variables: {
last_name: filterValue,
},
})
.valueChanges
.pipe(
map(returnedArray => {
// console.log('returnedArray in map: ', returnedArray); // All last_name's with the letter in them someplace.
const membersArray = returnedArray.data['lastNameSearch']; // extract items array from GraphQL JSON array
// For case insensitive search
const newArray = membersArray.filter(this.utilitiesService.filterBy(filterValue, 'last_name'));
return newArray;
})
)
.subscribe(result => {
this.membersComponent.dataSource.data = result;
});
} else {
// Filter the table instead of calling the db for each letter entered.
// Note: Apollo client doesn't seem able to query the cache with this kind of search.
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
// Interface and redefinition of filterPredicate in the ngOnInit
this.membersComponent.dataSource.filter = filterValue; // Filters all columns unless modifed by filterPredicate.
}
}
utilities.service.ts
// -------------- DATABASE COLUMN SEARCH -------------
// Shared with other components with tables.
// For case insensitive search.
// THIS NEEDS TO BE CLEANED UP BUT I'M MOVING ON, MAYBE LATER
public filterBy = (filterValue, column) => {
return (item) => {
const charTest = item[column].charAt(0);
if (charTest === filterValue.toLowerCase()) {
return true;
} else if (charTest === filterValue.toUpperCase()) {
return true;
} else {
return false;
}
}
};
In the following code, I am unable to understand why validateOpt might return value JsSuccess(None) instead of JsError
def getQuestion = silhouette.UserAwareAction.async{
implicit request => {
val body: AnyContent = request.body
val jsonBodyOption: Option[JsValue] = body.asJson
jsonBodyOption.map((jsonBody:JsValue) => { //body is json
val personJsonJsResultOption = jsonBody.validateOpt[Person]//check that json structure is correct
personJsonJsResultOption match {
case personSuccessOption: JsSuccess[Option[Person]] => { //json is correct
val personOption = personSuccessOption.getOrElse(None) //why would getOrElse return None??
personOption match {
case Some(person) => {
... }
case None =>{ //I am not sure when this will be triggered.
...
}
}
}
}
case e: JsError => {
...
}
}
}
})
.getOrElse(//body is not json
...)
}
}
validateOpt by design considers success to be not only when body provides actual Person but also when Person is null or not provided. Note how documentation explains why JsSuccess(None) is returned:
/**
* If this result contains `JsNull` or is undefined, returns `JsSuccess(None)`.
* Otherwise returns the result of validating as an `A` and wrapping the result in a `Some`.
*/
def validateOpt[A](implicit rds: Reads[A]): JsResult[Option[A]]
Seems like your requirement is that Person must always be provided to be considered successful, so in this case validate should be used instead of validateOpt.
First of all i wanna say sorry for that if my question is silly question,Iam confused with this because im new in Angular.
Before asking question i want to introduce about my code,
this is the get functon that exactly i have called api,
get(feepaid_report: FeepaidReport): Observable<FeepaidReport[]> {
const options = this._utils.makeOptions(this._headers);
return this._http.get(`${this._feepaidreportUrl}`, options).pipe(
map((res: Response) => res.json()),
tap(
data => this.afterGetRequest(),
error => { console.log(error); }
));
}
Here in this code _feepaidreportUrl is my baseUrl that looks like this:
private _feepaidreportUrl = `${new Config().api}/report/feepaid_report/`;
And the my argument feepaid_report of type FeepaidReport is comes with data of dictionary like this,
FeepaidReport: {paid_date: "2019-01-03", classes: "class12"}
And i want to append this dictionary (i.e feepaidreport data) in url so that i can pass the url for backend like that:
baseurl/?paid_date=2019-01-03&classes=class12
Hope you will understand my question
Above problem is solved by doing this:
get(feepaid_report: FeepaidReport): Observable<FeepaidReport[]> {
var url = `${this._feepaidreportUrl}/?`
for(var key in feepaid_report){
var val = feepaid_report[key];
if (typeof(val) !=='undefined'){
url = url + key + '=' + val + '&'
}
}
const options = this._utils.makeOptions(this._headers);
return this._http.get(url, options).pipe(
map((res: Response) => res.json()),
tap(
data => this.afterGetRequest(),
error => { console.log(error); }
));
}
I'm using Play Framework 2.2 and ReactiveMongo. I'm iterating trough all received entries from ReactiveMongo, and getting some property from single entry. Sometimes it throws Exception of inexistent property, how should I catch it, for now using simple "recover" doesn't work.
val cursor:Cursor[JsObject] = // QUERY FOR DATA
val processingData = cursor.enumerate().apply(Iteratee.foreach { doc =>
(doc \ "property")
}
processingData.map { data =>
Logger.info(s"$data")
None
}.recover {
case e =>
Logger.error(s"Error during parsing $e")
None
}
Iteratee.foreach always return Unit type, so value processingData will not contain data and enumerator apply some Iteratee only attach iteratee to emumerator, but don't run it. I think, this must solve your problem:
val cursor:Cursor[JsObject] = // QUERY FOR DATA
val getData = Enumeratee.mapM[JsObject]{doc =>
Future(doc \ "property") //use future to catch exception here
}
val processingData: Future[scala.List[JsObject]] = cursor.enumerate() &> getData .run Iteratee.getChunks
I am using Pase.com with js SDK for the backend of my Dart App. This works fine apart from the parse sdk accepts an object of callback functions. In dart Im unsure how to do this, I can get single callbacks working fine. But Im completely lost here.
Normal Parse JS for registering a user
var user = new Parse.User();
user.set("username", "my name");
user.set("password", "my pass");
user.set("email", "email#example.com");
// other fields can be set just like with Parse.Object
user.set("phone", "415-392-0202");
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
My Dart code
void registerSuccess(user) {
print("success");
}
void registerFailed(user, error){
print("fail");
}
void register(String email, String password)
{
js.scoped(() {
var parse = js.context.Parse;
var parseUser = new js.Proxy(parse.User);
parseUser.set("username", "my name");
parseUser.set("password", "my pass");
parseUser.set("email", "email#example.com");
print(parseUser.getEmail());
var callbackSuccess = new js.Callback.once(() => registerSuccess());
var callbackFailed = new js.Callback.once(() => registerFailed());
parseUser.signUp(null,{"success":callbackSuccess, "error": callbackFailed});
//parseUser.signUp();
});
}
Also the callback function needs accept vars passed back from the js.
Any help would be a appreciated, I have be spinning my wheels for 2 days on this.
Instead of :
var callbackSuccess = new js.Callback.once(() => registerSuccess());
var callbackFailed = new js.Callback.once(() => registerFailed());
parseUser.signUp(null,{"success":callbackSuccess, "error": callbackFailed});
use :
var callbackSuccess = new js.Callback.once(registerSuccess);
var callbackFailed = new js.Callback.once(registerFailed);
parseUser.signUp(null, js.map({"success":callbackSuccess, "error": callbackFailed}));