Any tutorial about express.js and deepstream work together [closed] - express

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
All:
As title asked, I am pretty new to Express and Deepstream, I wonder how can I make them work together( Or they have to work separately? )?
In Deepstream guide section ( https://deepstream.io/tutorials/integrations/ )
It only provides how to connect Frontend and Persistence layer, but not too much about how to co-work with other REST API service( only one small section: https://deepstream.io/tutorials/integrations/other-http/, but not too much user cases)
Any tutorial/Example( simple case like authorized chat and friend chat list )?
Thanks

Deepstream can currently be passed a http server to initialize its websocket server. However this behavior is being deprecated in the very near future as we want to further optimize deepstream.io by moving it more into the c++ space, meaning the http server will be able to handle much many more concurrent connections at the expense of not being configurable.
In most cases you can build your entire application using a deepstream client. The combination of data-sync, events and rpcs means that as long as you aren't looking at doing actions such as binary uploads/transfers you can benefit from picking the best tool to accomplish a task.
For example, you can use RPCs when requiring classic request/response atomic operations:
ds.rpc.provide( 'add-numbers', function( data, response ) {
var result = data.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
})
response.send( result )
} )
ds.rpc.make( 'add-numbers', [ 1, 3 ], function( err, data ) {
console.log( 'result: ', data )
} )
which is similar to express:
app.post( '/add-two', function( req, res ) {
var result = req.body.data.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
})
res.send( result )
} )
Except deepstream would also manage concepts such as service discovery and load balancing for you and even allow clients the opportunity to become endpoints if wanted.
or use events:
ds.event.emit( 'score-changed', score++ )
ds.event.subscribe( 'score-changed', function( newScore ) {
console.log( `The score changed on: ${newScore}` )
} )
or model your application data and synchronize it across all clients using records:
var record = ds.record.getRecord( 'playerA' )
record.subscribe( 'score', function( newScore ) {
console.log( `Player A score has changed to: ${newScore}` );
} );
record.set( 'score', record.get('score')++ );
I hope that helps!

Related

How can I get foreign exchange rates thru an API by using PHP or Ajax? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I need a foreign exchange rate API in PHP for my recent project, in which I need updates after 60 sec.I also need metals like Gold, Silver etc latest exchange rates. So anyone who can I guide me for a PHP endpoint providing latest exchange rates. Any help will be highly appreciated.
I'll strongly recommend you CurrencyFreaks API. It provides foreign currency exchange rate endpoint in multiple languages including PHP and Ajax. It's prominent features are:
Data is updated every 60 sec.
You can change the ‘Base’ currency.
It provides currency exchange rates for 179 currencies worldwide including currencies, metals (Gold, Silver, Palladium, Platinum), and cryptocurrencies.
Supported codes for the endpoints are Shell, Node.js, Java, Python,
PHP, Ruby, JS, C#, Go, C, Swift.
Here's the latest exchange rates endpoint using PHP:
setUrl('https://api.currencyfreaks.com/latest
?apikey=YOUR_APIKEY
&base=GBP
&symbols=EUR,USD,PKR,INR');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setConfig(array(
'follow_redirects' => TRUE
));
try {
$response = $request->send();
if ($response->getStatus() == 200) {
echo $response->getBody();
}
else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
}
catch(HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
For Ajax:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.currencyfreaks.com/latest
?apikey=YOUR_APIKEY
&base=GBP
&symbols=EUR,USD,PKR,INR");
xhr.send();
You can also get foreign exchange rate endpoint in other programming languages from here: https://currencyfreaks.com/documentation.html#Latest
I hope this solution will help for your recent project.

GET request that triggers PATCH request (express) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
On my express server I have a script which retrieves items through scraping. I want to trigger this script once in a while and push the retrieved items into my database.
My first ideas was to create an endpoint in my API (e.g. /api/scrape-items). The problem is that it would be a GET request responsible for running the script, retrieving the items AND PATCH the items (update) my database. It doesn't seem right to let a GET request do all of that, especially to make a PATCH request, but I can't change the GET request to a POST request either because I have no body.
Can someone help me come up with a better approach? Thanks!
UPDATE: Example of triggering endpoint:
router.get('/scrape-items/', async (req, res) => {
try {
const resultFromScraping = await [
{ id: 1, data: 'updated data' },
{ id: 2, data: 'updated data' }
]
await Promise.all(
resultFromScraping.map(
async item =>
await axios.patch(
`/api/items/${item.id}`,
item.data
)
)
)
} catch (err) {
res.status(500).json({ message: err.message })
}
})
A POST request is perfectly acceptable for uploading content to a database. PATCH is usually reserved for when you are partially updating and item. So if you are just updating stuff in your database with this request, then don't hesitate to use PATCH. If you are completely replacing the resource in the database though (or you require the entire resource in the HTTP request, not just the modified stuff), then I'd recommend using PUT instead.
A GET request would be acceptable as well in this situation if you were returning data to the user.

IBM Cloud Object Storage - can the order be made using API? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Is it possible for customers to make IBM ’could-object-storage' orders via API? It will be great if related guidance or samples can be provided. Ordering IBM Cloud Object Storage is described in knowlegelayer, but it seems that there is not any info about doing it via API.
Yes, it is possible. You can read more information here Managing-SoftLayer-Object-Storage-Through-REST-APIs
Currently, SoftLayer Control portal uses package 206 to order could-object-storage S3 and SWIFT types. To know the item prices you can perform following REST call.
https://[userName]:[apiKey]#api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/206/getItemPrices
Use the service SoftLayer_Product_Order::verifyOrder to verify the order and use SoftLayer_Product_Order::placeOrder when you ready to order.
Order a S3 object storage type
You need to send a SoftLayer_Container_Product_Order_Network_Storage_Object object as following:
https://[userName]:[apiKey]#api.softlayer.com/rest/v3.1/SoftLayer_Product_Order/verifyOrder
Method: POST
Body:
{
"parameters" : [
{
"complexType": "SoftLayer_Container_Product_Order_Network_Storage_Object",
"quantity": 1,
"packageId": 206,
"prices": [ { "id": 1111111 }]
}
]
}
Note: Change [userName], [apiKey], and 111111 with your own data. Replace verifyOrder by placeOrder when you ready to order.
Order a SWIFT object storage
On this case you need to send a SoftLayer_Container_Product_Order_Network_Storage_Hub object. Following is an example:
https://[userName]:[apiKey]#api.softlayer.com/rest/v3.1/SoftLayer_Product_Order/verifyOrder
Method: POST
Body:
{
"parameters" : [
{
"complexType": "SoftLayer_Container_Product_Order_Network_Storage_Hub",
"quantity": 1,
"packageId": 206,
"prices": [ { "id": 222222 }]
}
]
}
Note: Change [userName], [apiKey], and 222222 with your own data. Replace verifyOrder by placeOrder when you ready to order.
I hope this help you.

Podio - updating item field results in empty field [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to update an item field value in Podio via AJAX request - I can make the requests successfully, but rather than updating the field value to the value passed in the request, the item field in Podio is simply emptied (as though updated to an empty value). Here's the call:
$.ajax({
type:'PUT',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'OAuth2 ' + response.access_token)
},
url:'https://api.podio.com/item/654321/value/12345',
data: JSON.stringify({'value': 'new_value'})
}).done(function(response){
console.log(response)
}).fail(function(error){
console.log(error)
})
But the result of this will be to simply erase the old field value. Close, but no cigar.
How should the data attribute be formatted for Podio to correctly update the field value?
(I understand that there are a number of Podio client libraries that can help with this, but they are not useful to us in our current situation - we need to handle this process via good ol' AJAX)
Got it - it was an easy fix, just had to set the contentType. Silly me.
$.ajax({
type:'PUT',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'OAuth2 ' + response.access_token)
},
contentType: 'application/json',
url:'https://api.podio.com/item/654321/value/12345',
data: JSON.stringify({'value': 'new_value'})
}).done(function(response){
console.log(response)
}).fail(function(error){
console.log(error)
})

REST URIs for a Rule Engine (stateless engine) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need some guidance for designing REST URIs for a rule engine. There are a set of rules defined and stored in the back-end system in the form of XML files. These rules are grouped into various categories and a set of rules get executed based on the category specified by the user. The user passes a set of user selections/options and category as input to the rule engine. The rule engine executes the rules belonging to the category against the user selections/options. These are process/compute like operations which doesn't involve persistence of user state into the system. On a whole, the user state is not maintained in the rule engine... ie., a stateless rule engine.
I am trying to design REST APIs for rule engine execution (rule creation part is already taken care of):
The operation doesn't Create, Update, Delete any serve side resources.
The rules are executed against the user selections.
User selections can be complex (hierarchical structure) and it can't modeled as URI params.
Request your guidance is designing a REST URI pattern considering the above mentioned aspects.
To get a rules belonging to a category:
GET /rule_category/{id}
To process user selections in the context of rules (rule execution by rule engine):
POST /rule_engine
BODY to contain a JSON structure with rule category & user selections
Please provide your suggestions on the above URI design and any other possible URIs for the above mentioned use case. Should PUT/POST be used for rule execution URI?
EDIT 1: Adding the sample JSON/XML structure that encapsulates rule category and user selection info:
{
processdata:{
rulecategory:'ruleCat1',
userselections:{
userselection:[
{
item:'us1'
},
{
item:'us2'
},
{
item:'us3',
customselection:{
value:'cs1'
}
}
]
}
}
}
<ProcessData RuleCategory="ruleCat1">
<UserSelections>
<UserSelection Item="us1"/>
<UserSelection Item="us2"/>
<UserSelection Item="us3">
<CustomSelection Value="cs1"/>
</UserSelection>
</UserSelections>
REST is not Remote Procedure Call (RPC). REST is about Resources.
If you want to have a RESTful API that handles computations, model computations as resources.
Create a new computation resource
Request
POST /computations
Content-Type: application/json
{
// the selected rules etc.
}
Response
201 Created
Location: /computations/748A9FC0-B74E-11E4-8822-4D7FDD9DA696
where 748A9FC0-B74E-11E4-8822-4D7FDD9DA696 is the ID of this computation generated by the server.
Get the state of the computation
Request
GET /computations/748A9FC0-B74E-11E4-8822-4D7FDD9DA696
Response: still computing
200 OK
Content-Type: application/json
{
"id": "748A9FC0-B74E-11E4-8822-4D7FDD9DA696",
"data": { ... },
"state": "computing"
}
Response: finished
200 OK
Content-Type: application/json
{
"id": "748A9FC0-B74E-11E4-8822-4D7FDD9DA696",
"data": { ... },
"state": "finished",
"result": {
// details about the result
}
}
Your only options is POST in this case.
Be aware that REST has constraints e.g. uniform interface constraint, which includes HATEOAS. So you have to send links to your clients, which they can follow. In this case you will have hard time to explain the (machine) clients how to assemble the body of your request. A possible way to overcome this, is defining your application specific request media type.
So it is possible to solve this with REST, but I think you will work in this case much more than you would by an RPC. I agree with Lutz, you should not use REST by your Rule Engine if you don't have other resources which state are kept on the server.