Trying to create an equivalent for decodeEvent using rescript-json-combinators. I couldn't figure out how to replace "Decoder(decoder)" since Decoders have been made abstract in rescript-json-combinators. Trying to use Decode.decode didn't work.
Any idea on how this could be solved?
let decodeEvent = (Decoder(decoder), value: Web_node.event) =>
try decoder(Obj.magic(value)) catch {
| ParseFail(e) => Error(e)
| _ => Error("Unknown JSON parsing error")
}
The purpose of decodeEvent seems to be two-fold:
To convert a Web_node.event to Json.t in order to use Json decoders on it.
To return a result instead of raising an exception on error.
The rescript-json-combinators API already has a result-based API. That's part of the reason why the implementation is now hidden and requires the use of Json.decode to run the decoders. That seems to be all that's missing here:
let decodeEvent = (decoder, value: Web_node.event) =>
value->Obj.magic->Json.decode(decoder)
Related
I need some help to figure it our why I am getting error when using macthes API, this is my code:
export async function searchCars(query) {
await connect();
const repository = client.fetchRepository(schema);
const cars = await repository
.search()
.where("make")
.eq(query)
.or("model")
.eq(query)
.or("description")
.matches(query)
.return.all();
return cars;
}
And I am getting this error when making API request
May I ask for help?
Many thanks ~~
I did remove the macthes() API, the whole query works, and I can get results back.
If i add it back, the APi will return redis error ...
Expectation: I would like to do text search which matches the paragraph text, then return the record(s).
Sorry, I think I have figured it our, the issue is we need to ensure the scheme field type must be text rather than string, something like below:
description: { type: "text", textSearch: true },
Here's the problem I'm having with tauri.
'return' shows you the return value I need, and I know for a fact that writing it this way does not work at all.
'pick_file' is called asynchronously, and I know that message passing seems to work, but is there an easier way to get the value I need.
#[tauri::command]
fn open_file() -> String {
dialog::FileDialogBuilder::default()
.add_filter("data", &["json"])
.pick_file(|path_buf| match path_buf {
Some(p) => return format!("{}", p.to_str().unwrap()),
_ => return "".into()
});
}
First, return in a closure returns from the closure and not from the function that contains it.
The more fundamental issue is that you can't return a String from open_file() if you use FileDialogBuilder::pick_file(). According to the documentation, pick_file() is non-blocking and returns immediately without waiting for the user to pick the file. What you can do in the closure is send the file down a channel, and pick it up elsewhere.
Please would you kindly guide me in the right direction?
I am trying to pull records from an old Http REST service, restructure the data, then post it to firebase.
I'm not sure if this is the completely wrong approach or I misunderstand observable's completely. Your guidance will be most appreciated. How to send this new listing to another DataService function: exportToFirebase(new_listing) ?
onServiceCall() {
this.httpDataService.getData().subscribe((itemData) => {
this.itemDataJSON = itemData;
if (this.itemDataJSON) {
this.itemDataJSON.forEach(function(value) {
let new_listing = new Listing(value.id, value.name, value.category);
//console.log(new_listing);
//How to send this new listing to another firebaseDataService function exportToFirebase(new_listing);
});
}
});
}
This demo does what you want, using mocked http & firebase services.
// --- make http call
httpCall.pipe(
// --- construct an array of "new_listing" (of just one, up to u) and pass along the observable chain
concatMap(httpNumbers => of(...httpNumbers)),
// --- make the firebase call
concatMap(number => firebaseCall(number))
).subscribe(val => console.log(val))
Hope this helps. If this does not make sense, then you need to read up on RxJS.
Using the motion-firebase library for RubyMotion Firebase (https://github.com/colinta/motion-firebase) I can set data easy enough either by doing:
firebase.set({ full_name: ['first_name' => 'Fred', 'last_name' => 'Flintstone'] })
or
firebase['first_name'] = 'Fred'
But I'm having trouble figuring out how to retrieve data.
I've tried the different firebase.query methods listed in the reponse readme but I'm definitely missing something.
I'd hoped it would be as simple as:
firebase.query['first_name']
=> 'Fred'
Could someone please explain how I might go about querying Firebase with a key and returning the value.
colinta here! You'll need to attach an observer (https://github.com/colinta/motion-firebase#attaching-observers-to-read-data).
firebase_ref.once(:value) { |snapshot| snapshot.value }
See https://www.firebase.com/docs/ios-api/Classes/FDataSnapshot.html for info on the FDataSnapshot type.
linuxfood has created bindings for sqlite3, for which I am thankful. I'm just starting to learn Rust (0.8), and I'm trying to understand exactly what this bit of code is doing:
extern mod sqlite;
fn db() {
let database =
match sqlite::open("test.db") {
Ok(db) => db,
Err(e) => {
println(fmt!("Error opening test.db: %?", e));
return;
}
};
I do understand basically what it is doing. It is attempting to obtain a database connection and also testing for an error. I don't understand exactly how it is doing that.
In order to better understand it, I wanted to rewrite it without the match statement, but I don't have the knowledge to do that. Is that possible? Does sqlite::open() return two variables, or only one?
How can this example be written differently without the match statement? I'm not saying that is necessary or preferable, however it may help me to learn the language.
The outer statement is an assignment that assigns the value of the match expression to database. The match expression depends on the return value of sqlite::open, which probably is of type Result<T, E> (an enum with variants Ok(T) and Err(E)). In case it's Ok, the enum variant has a parameter which the match expression destructures into db and passes back this value (therefore it gets assigned to the variable database). In case it's Err, the enum variant has a parameter with an error object which is printed and the function returns.
Without using a match statement, this could be written like the following (just because you explicitly asked for not using match - most people will considered this bad coding style):
let res = sqlite::open("test.db");
if res.is_err() {
println!("Error opening test.db: {:?}", res.unwrap_err());
return;
}
let database = res.unwrap();
I'm just learning Rust myself, but this is another way of dealing with this.
if let Ok(database) = sqlite::open("test.db") {
// Handle success case
} else {
// Handle error case
}
See the documentation about if let.
This function open returns SqliteResult<Database>; given the definition pub type SqliteResult<T> = Result<T, ResultCode>, that is std::result::Result<Database, ResultCode>.
Result is an enum, and you fundamentally cannot access the variants of an enum without matching: that is, quite literally, the only way. Sure, you may have methods for it abstracting away the matching, but they are necessarily implemented with match.
You can see from the Result documentation that it does have convenience methods like is_err, which is approximately this (it's not precisely this but close enough):
fn is_err(&self) -> bool {
match *self {
Ok(_) => false,
Err(_) => true,
}
}
and unwrap (again only approximate):
fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) => fail!(),
}
}
As you see, these are implemented with matching. In this case of yours, using the matching is the best way to write this code.
sqlite::open() is returning an Enum. Enums are a little different in rust, each value of an enum can have fields attached to it.
See http://static.rust-lang.org/doc/0.8/tutorial.html#enums
So in this case the SqliteResult enum can either be Ok or Err if it is Ok then it has the reference to the db attached to it, if it is Err then it has the error details.
With a C# or Java background you could consider the SqliteResult as a base class that Ok and Err inherit from, each with their own relevant information. In this scenario the match clause is simply checking the type to see which subtype was returned. I wouldn't get too fixated on this parallel though it is a bad idea to try this hard to match concepts between languages.