How to join two API in Angular 2 - javascript

I want to simulate a micro blogging application to learn Angular 2.
I am using the following json placeholder links:
users
post
As you can see, the post api has userId, (and not username). If I have to display the user name while listing all post, would I require another API with both post and user name, or can it be done using two different calls to the above APIs?
This is the way I will be listing the post :-
<li *ngFor="let post of posts">
<div>{{post.userId}}</div>
<div>{{post.id}}</div>
<div>{{post.title}}</div>
<div>{{post.body}}</div>
</li>
As you can see, here based on the api call, I am getting userId...Instead of that I want it to display user's name

The way to do this in angular is using services. You don't directly call to an API from within your component. You need to create a "service" to deal with APIs, then inject your service in your component and consume them in there.
In your particular scenario, you will have two services, a "UserService" and a "PostService". Each of those services have a proper "get" method that calls to an API. Then in your component, you inject both those services and call their respective methods separately.
Regarding your specific update on the question, imagine you have a "posts" array and a "users" array after you have received your result from the API. Now, pay attention to the following logic:
for (let i=0; i<posts.length; i++)
{
posts[i].username = users.filter(u => u.id === posts[i].userId)[0].username
}
What we did here is iterating through all "posts" and adding a "username" attribute to each of them by cross referencing them to the users array. Just make sure you use the right syntax and case sensitivity as I have not tested this line and just included the logic in it

Both the options are viable..
You can create another API that responds with the required data. The new API can cal the controller functions of the previous API endpoints and return the data in the required format.
note: this is possible if you are working with your own server.
you can also chain the API calls if you want to work with the existing APIs.. Call the user api and then when you get the user details, in the subscribe handler, make another request to the posts API.
note the only problem i can see with this approach is the number of requests.. as there will be a posts request for each user.
In the End the decision is yours. you'll have to see the pros and cons.. If the server code is also yours, ill suggest the first approach..

Related

SAP B1 Service Layer JavaScript Extensibility SQLQueries

I am triying to use SQLQueries using Service Layer JavaScript Extension to get some info from table OCRD (field DocEntry) beacuse is not expossed in stanard CRUD entities (BusinessPartners). Is there a way to do it? I can retrieve the information by Postman, but I am unable to do it using JavaScript.
Thank you
Unique key for Business Partners is CardCode, and this one is exposed with the BP object, of course.
DocEntry, which can be queried from OCRD using SQL, is not exposed within SL's BusinessPartner object.
In Working with SAP Business One Service Layer user manual - has this in it:
To run the query, there are two ways in the Service Layer: one is to set a payload using POST and the other is to
specify a query parameter using GET.
By POST
POST https://server:50000/b1s/v1/SQLQueries('sql01')/List HTTP/1.1
{
"ParamList": "docTotal=10.1"
}
By GET
GET https://server:50000/b1s/v1/SQLQueries('sql07')/List?docTotal=10.1 HTTP/1.1

Making really simple app including front & backend skills (js, node.js, psql, react...)

I'm trying to make a simple todo app in order to understand how frontend and backend are connected. I read some of the websites showing a tutorial for using and connecting rest API, express server, and database, but still, I was not able to get the fake data from a database. Anyway, I wanted to check if my understanding of how they are connected and talk to each other is correct or not. So could you give some advice please?
First of all, I'm planning to use either Javascript & HTML or React for frontend, Express for server, and Postgres for the database. My plan is a user can add & delete his or her task. I have already created a server in my index.js file and created a database using psql command. Now if I type "" it takes me to the page saying "Hello" (I made this endpoint), and I'm failing to seed my data to the database. Here are my questions↓
After I was able to seed my fake data into the database, how should I get the data from the database and send to the frontend? I think in my index.js file, create a new endpoint something like "app.get("/api/todo", (res, req) => ..." and inside of the callback function, I should write something like "select * from [table name]". Also, form the front end, I should probably access certain endpoints using fetch. Is this correct?
Also, how can I store data which is sent from the frontend? For example, if I type my new todo to <input> field and click the add <button>, what is the sequence of events looks like? Adding event listener to button and connect to the server, then create post method in the server and insert data, kind of (?) <= sorry this part it's super unclear for me.
Displaying task on the frontend is also unclear for me. If I use an object like {task: clean up my room, finished: false (or 0 ?)} in the front end, it makes sense but, when I start using the database, I'm confused about how to display items that are not completed yet. In order to display each task, I won't use GET method to get the data from the database, right?
Also, do I need to use knex to solve this type of problem? (or better to have knex and why?)
I think my problem is I kind of know what frontend, server, database for, but not clear how they are connected with each other...
I also drew some diagrams as well, so I hope it helps you to understand my vague questions...
how should I get the data from the database and send to the frontend?
I think in my index.js file, create a new endpoint something like
"app.get("/api/todo", (res, req) => ..." and inside of the callback
function, I should write something like "select * from [table name]".
Typically you use a controller -> service -> repository pattern:
The controller is a thin layer, it's basically the callback method you refer to. It just takes parameters from the request, and forwards the request to the service in the form of a method call (i.e. expose some methods on the service and call those methods). It takes the response from the service layer and returns it to the client. If the service layer throws custom exceptions, you also handle them here, and send an appropriate response to the client (error status code, custom message).
The service takes the request and forwards it to the repository. In this layer, you can perform any custom business logic (by delegating to other isolated services). Also, this layers will take care of throwing custom exceptions, e.g. when an item was not found in the database (throw new NotFoundException)
The repository layer connects to the database. This is where you put the custom db logic (queries like you mention), eg when using a library like https://node-postgres.com/. You don't put any other logic here, the repo is just a connector to the db.
Also, form the front end, I should probably access certain endpoints
using fetch. Is this correct?
Yes.
Also, how can I store data which is sent from the frontend? For
example, if I type my new todo to field and click the add , what is
the sequence of events looks like? Adding event listener to button and
connect to the server, then create post method in the server and
insert data, kind of (?) <= sorry this part it's super unclear for me.
You have a few options:
Form submit
Ajax request, serialize the data in the form manually and send a POST request through ajax. Since you're considering a client library like React, I suggest using this approach.
Displaying task on the frontend is also unclear for me. If I use an
object like {task: clean up my room, finished: false (or 0 ?)} in the
front end, it makes sense but, when I start using the database, I'm
confused about how to display items that are not completed yet. In
order to display each task, I won't use GET method to get the data
from the database, right?
If you want to use REST, it typically implies that you're not using backend MVC / server rendering. As you mentioned React, you're opting for keeping client state and syncing with the server over REST.
What it means is that you keep all state in the frontend (in memory / localstorage) and just sync with the server. Typically what is applied is what is referred to as optimistic rendering; i.e. you just manage state in the frontend as if the server didn't exist; yet when the server fails (you see this in the ajax response), you can show an error in the UI, and rollback state.
Alternatively you can use spinners that wait until the server sync is complete. It makes for less interesting user perceived performance, but is just as valid technical wise.
Also, do I need to use knex to solve this type of problem? (or better
to have knex and why?) I think my problem is I kind of know what
frontend, server, database for, but not clear how they are connected
with each other...
Doesn't really matter what you use. Personally I would go with the stack:
Node Express (REST), but could be Koa, Restify...
React / Redux client side
For the backend repo layer you can use Knex if you want to, I have used node-postgres which worked well for me.
Additional info:
I would encourage you to take a look at the following, if you're doubtful how to write the REST endpoints: https://www.youtube.com/watch?v=PgrP6r-cFUQ
After I was able to seed my fake data into the database, how should I get the data from the database and send to the frontend? I think in my index.js file, create a new endpoint something like "app.get("/api/todo", (res, req) => ..." and inside of the callback function, I should write something like "select * from [table name]". Also, form the front end, I should probably access certain endpoints using fetch. Is this correct?
You are right here, you need to create an endpoint in your server, which will be responsible for getting data from Database. This same endpoint has to be consumed by your Frontend application, in case you are planning to use ReactJS. As soon as your app loads, you need to get the current userID and make a fetch call to the above-created endpoint and fetch the list of todos/any data for that matter pertaining to the concerned user.
Also, how can I store data which is sent from the frontend? For example, if I type my new todo to field and click the add , what is the sequence of events looks like? Adding event listener to button and connect to the server, then create post method in the server and insert data, kind of (?) <= sorry this part it's super unclear for me.
Okay, so far, you have connected your frontend to your backend, started the application, user is present and you have fetched the list of todos, if any available for that particular user.
Now coming to adding new todo the most minimal flow would look something like this,
User types the data in a form and submits the form
There is a form submit handler which will take the form data
Check for validation for the form data
Call the POST endpoint with payload as the form data
This Post endpoint will be responsible for saving the form data to DB
If an existing todo is being modified, then this should be handled using a PATCH request (Updating the state, if task is completed or not)
The next and possibly the last thing would be to delete the task, you can have a DELETE endpoint to remove the todo item from the list of todos
Displaying task on the frontend is also unclear for me. If I use an object like {task: clean up my room, finished: false (or 0 ?)} in the front end, it makes sense but, when I start using the database, I'm confused about how to display items that are not completed yet. In order to display each task, I won't use GET method to get the data from the database, right?
Okay, so as soon as you load the frontend for the first time, you will make a GET call to the server and fetch the list of TODOS. Store this somewhere in the application, probably redux store or just the application local state.
Going by what you have suggested already,
{task: 'some task name', finished: false, id: '123'}
Now anytime there has to be any kind of interaction with any of the TODO item, either PATCH or DELETE, you would use the id for each TODO and call the respective endpoint.
Also, do I need to use knex to solve this type of problem? (or better to have knex and why?) I think my problem is I kind of know what frontend, server, database for, but not clear how they are connected with each other...
In a nutshell or in the most minimal sense, think of Frontend as the presentation layer and backend and DB as the application layer.
the overall game is of sending some kind of request and receiving some response for those sent requests. Frontend is what enables any end-user to create these so-called requests, the backend (server & database) is where these requests are processed and response is sent back to the presentational layer for the end user to be notified.
These explanations are very minimal to make sure you get the gist of it. Since this question almost revolves around the entire scope of web development. I would suggest you read a few articles about both these layers and how they connect with each other.
You should also spend some time understanding what is RESTful API. That should be a great help.

How can I keep both users tables "synchronized" using BackAnd?

I'm good with registering users, login, etc.
Now I'm getting into modifying users with:
this.backand.object.update('users', user.userId, user)
but I can see that only my table gets modified, while I'll also need to modify the "Registered Users" table existing in "Security & Auth > Registered Users".
I understand I might need to create a custom action...maybe "Before Update"? ...but I can't find documentation on how to modify that specific table (via API or via BackAnd actions).
Thank you.
thanks for using Backand! We don't offer any methods via the SDK to update the registered users. You can use the HTTP object to send a call to the back-end's REST API directly, hitting the same URL that the SDK requests when creating a new user, but this isn't officially documented. In general, we try to limit direct modifications of the registered users table, as there are some security concerns regarding how frequently the data is accessed and modified, but you can access the users object directly via the /users URL. There is an article in our documentation at http://docs.backand.com/en/latest/apidocs/security/index.html#link-your-app-39-s-users-with-backand-39-s-registered-users that covers an automated process for making these kinds of changes - you should be able to adapt some of the server side code in that example to work with your use case.
One alternative that would work now would be to have any change in basic information (username, password, firstname, lastname) result in a new user being created, and you could then use a custom action to perform the migration to the new user, but that is unnecessarily complex. I will add a ticket for our developers to look at adding this registered user management functionality in the future.

What is the most efficient way to make a batch request to a Firebase DB based on an array of known keys?

I need a solution that makes a Firebase DB API call for multiple items based on keys and returns the data (children) of those keys (in one response).
Since I don't need data to come real-time, some sort of standard REST call made once (rather than a Firebase DB listener), I think it would be ideal.
The app wouldn't have yet another listener and WebSocket connection open. However, I've looked through Firebase's API docs and it doesn't look like there is a way to do this.
Most of the answers I've seen always suggest making a composite key/index of some sort and filter accordingly using the composite key, but that only works for searching through a range. Or they suggest just nesting the data and not worrying about redundancy and disk space (and it's quicker), instead of retrieving associated data through foreign keys.
However, the problem is I am using Geofire and its query method only returns the keys of the items, not the items' data. All the docs and previous answers would suggest retrieving data either by the real-time SDK, which I've tried by using the once method or making a REST call for all items and filter with the orderBy, startAt, endAt params and filtering locally by the keys I need.
This could work, but the potential overhead of retrieving a bunch of items I don't need only to filter them out locally seems wasteful. The approach using the once listener seems wasteful too because it's a server roundtrip for each item key. This approach is kind of explained in this pretty good post, but according to this explanation it's still making a roundtrip for each item (even if it's asynchronously and through the same connection).
This poor soul asked a similar question, but didn't get many helpful replies (that really address the costs of making n number of server requests).
Could someone, once and for all explain the approaches on how this could be done and the pros/cons? Thanks.
Looks like you are looking for Cloud Functions. You can create a function called from http request and do every database read inside of it.
These function are executed in the cloud and their results are sent back to the caller. HTTP call is one way to trigger a Cloud Function but you can setup other methods (schedule, from the app with Firebase SDK, database trigger...). The data are not charged until they leave the server (so only in your request response or if you request a database of another region). Cloud Function billing is based on CPU used, number of invocations and running intances, more details on the quota section.
You will get something like :
const database = require('firebase-admin').database();
const functions = require('firebase-functions');
exports.getAllNodes = functions.https.onRequest((req, res) => {
let children = [ ... ]; // get your node list from req
let promises = [];
for (const i in children) {
promises.push(database.ref(children[i]).once('value'));
}
Promise.all(promises)
.then(result => {
res.status(200).send(result);
})
.catch(error => {
res.status(503).send(error);
});
});
That you will have to deploy with the firebase CLI.
I need a solution that makes a Firebase DB API call for multiple items based on keys and returns the data (children) of those keys (in one response).
One solution might be to set up a separate server to make ALL the calls you need to your Firebase servers, aggregate them, and send it back as one response.
There exists tools that do this.
One of the more popular ones recently spec'd by the Facebook team is GraphQL.
https://graphql.org/
Behind the scenes, you set up your graphql server to map your queries which would all make separate API calls to fetch the data you need to fit the query. Once all the API calls have been completed, graphql will then send it back as a response in the form of a JSON object.
This is how you can do a one time call to a document in javascript, hope it helps
// Get a reference to the database service
let database = firebase.database();
// one time call to a document
database.ref("users").child("demo").get().then((snapshot) => {
console.log("value of users->demo-> is", snapshot.node_.value_)
});

RESTful API design with associations

I'm attempting to build an API for two resources, one with Users, and the other with Movies. Both resources have associations -- a User will have multiple Movies, and a Movie will have multiple Users. Presumably, I'd design my API something like this:
/api/users/
/api/users/:id
/api/users/:id/movies
/api/movies/
/api/movies/:id
/api/movies/:id/users
But here's the issue: I'm also using Backbone.js on the client side to fetch the API data. If If I create a Collection at
/api/users/:id/movies
then this will work well for GET requests, but POST and PUT requests would seemingly then be directed at:
/api/users/:id/movies/:id
But, seemingly, it would be better if it was posted to
/api/movies/:id
instead. Is that correct? How do people generally deal with RestFul associations?
Not sure what you mean by "POST and PUT requests would seemingly then be directed at...". Does Backbone.js automatically adds parameters to URLs? If so, you should look at configuring it so that it doesn't do that, because it won't be usable with a REST API. Links provided by a REST API should be the full ones, there's nothing to add or remove from them.
Finally, if you want to associate a movie with a user. You would POST the movie (or just its ID) to:
/api/users/:id/movies
It is correct. This is because "movies" are independent from "users". Movies can exist without users, so their relationship are actually "associative".
To create movies, you don't need users at all, so it makes more sense for the POST URI to create movie to be "POST /api/movies".
Alternative of association in RESTful API that I can think of is to have the list of movie IDs in the GET users API response, e.g. a property named "associatedMovieIDs" which has an array of strings of the IDs of the movies associated to the user.
With this, your APIs will then become:
/api/users/
/api/users/:id
/api/movies/
/api/movies/:id

Categories