Git API fetch users filtered by username - github-api

I'm searching for a mechanism to filter users by prefix. For Git API we can fetch the users filtered by location, exact name etc. But can we filter the list of users by prefix? For example fetch all the users whose username starts with "jo".

There is no way to guarantee these results, however I would suggest you use GitHub's GraphQL API and perform a search query. The following query is the best to get the results you want.
{
search(query: "jo", type: USER, first: 10) {
edges {
node {
... on User {
name
login
}
}
}
}
}
You can try it out on the Explorer here.

Related

Mongo function to find if superstring exists in array. Nodejs,

A document in my mongo 'companies' collection looks like this:
{
"companyName": "",
"companyIcon": "",
"domains": [
"companyDomainA.com",
"companyDomainB.dev"
],
"allowSubDomains": true
}
In my application the user enters his/her email address.
Using the Nodejs native mongo driver (https://mongodb.github.io/node-mongodb-native), I want to query (find) which company the user belongs to.
The problem is when the user enters the email as name#dept.companyDomainA.com.
I want to be able to query and find the company document of the user based on his email (subdomained 0 or more levels), ie. if the superstring of a string exists in an array in mongo.
(Caveat, I cannot store all the subdomains of the company as they are dynamic and can change at will)
Is there a regular expression way/db schema change way, to achieve this?
Thanks in advance!!
I would do it like this. First find the root domain from the email address. To do that I would split the email and fetch the domain first.
const email = "name#dept.companyDomainA.com";
const domain = email.split('#')[1]; // dept.companyDomainA.com
Now fetch the host (companyDomainA.com) from it. Follow this link.
So, I have found the root domain which is companyDomainA.com. Now run the find query.
db.collection('documents').find({"domains": "companyDomainA.com"});
I didn't test this code.

Which HTTP Method to Choose When Building Restful API

I am new to node.js and have my first node.js Restful API built in hapi.js framework. All the services do is basically doing database query. An example of the services is like this:
let myservice = {
method: "POST",
path: "/updateRule",
config: {
handler: (request, reply) => {
updateRule(request.payload)
.then((result) => {
reply(successResponse(request, result));
})
.catch((err) => reply(failResponse(request, err)).code(500));
},
validate: {
payload: {
ruleId: joi.number().required(),
ruleName: joi.string().required(),
ruleDesc: joi.string().required()
}
},
auth: "jwt",
tags: ["api", "a3i"]
},
}
updateRule(input): Promise<any> {
return new Promise((resolve, reject) => {
let query = `select a3i.update_rule(p_rul_id := ${input.ruleId}, p_rul_name := '${input.ruleName}', p_rul_desc := '${input.ruleDesc}')`;
postgresQuery(lbPostgres, query, (data, commit, rollback) => {
try {
let count = data.rows[0].update_rule.count;
if (count === 1) {
let ruleId = data.rows[0].update_rule.result[0];
let payload: SuccessPayload = {
type: "string",
content: `Rule ${ruleId} has been updated`
};
commit();
resolve(payload);
} else {
let thisErr = new Error("No rule can be found.");
thisErr.name = "4003";
throw thisErr;
}
}
catch (err) {
rollback();
if (err.name === "4003") {
reject(detailError(4003, err.message));
} else {
reject(detailError(4001, err.message));
}
}
}, reject);
});
}
As you can see, when the service is called, it evokes a database call (query) and updates specified row in database table. Similarly, I have other services named createRule/deleteRule creating/deleting records in database table. In my opinion, the difference between the services is doing different database query. I read this post PUT vs. POST in REST but couldn't see any difference of POST and PUT in my case.
Here are my questions:
What HTTP method should I used in this case?
Most of Restful API examples (for example https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd) use the same URL with different HTTP methods to do different operations on same "resource", which in my opinion is usually a database table. What's the benefit of this architecture compared with my practice in which one URL only has one HTTP method and only do one type of operation?
I know this question does not refer to a problem and is not specific. Some people may give it a down-vote. But as a beginner I really want to know what's a typical Restful API and make sure my API is "best practice". Please help!
If the resource already exists and thus you have a specific URI to that exact resource and you want to update it, then use PUT.
If the resource does not exist yet and you want to create it and you will let the server pick the URI that represents that new resource, then use POST and the POST URI will be a generic "create new resource" URI, not a URI to a specific resource and it will create the URI that represents that resource.
You can also use PUT to create a new resource if the caller is going to create the resource URI that represents the new resource. In that case, you would just PUT to that new resource and, if a resource with that URI already exists, it would be updated, if not, it would be created.
You do not have to support both. You can decide to make your api work in a way that you just use one or the other.
In your specific case, an update of a specific row in your database that already exists would pretty much always be a PUT because it already exists so you're doing a PUT to a specific URI that represents that row.
What's the benefit of this architecture compared with my practice in which one URL only has one HTTP method and only do one type of operation?
It's really up to you how you want to present your API. The general concept behind REST is that you have several components:
resource identifier
data
method
In some cases, the method can be subsumed by GET, PUT, POST or DELETE so you just need the resource identifier, data and GET, PUT, POST or DELETE.
In other cases or other designs, the method is more detailed than can be expressed in just a PUT or POST, so you have a method actually in the URL in which case, you may not need the distinction between PUT and POST as much.
For example, an action might be "buy". While you could capture that in a POST where the method is implied by the rest of the URL, you may want to actually POST to a URL that has a method in it: /buy for clarity and then you may use that same endpoint prefix with other methods such as /addToCart, etc... It really depends upon what the objects are in your REST design and what operations you want to surface on them. Sometimes, the objects lends themselves to just GET, PUT, POST and DELETE and sometimes, you want more info in the URL as to the specific operation to be carried out on that resource.
If you want to be Rest compliant, you can just use Post and Get.
If you want to be Restfull, you need to base your method on the CRUD
Create -> Post
Read -> Get
Update -> Put or Patch
Delete -> Delete
About building a full API, using method on the same URL could be easier to build / understand. All queries about your user will be on the user url and not user/get, user/add, user/update ... It let you have the same functionality, without too much different URL.
When you build an API, you will want to have some logs, for stats analysis and other stuff. This way, if you split with your method, you can just have a filter to logs how many Post requests, or Get requests.
In fact, you could build an API only with Get requests too. But spliting with methods and URL is the best way to avoid complexes URL (or URL with too much action name) and to have an easiest way to log every requests going through your API
- List item
Level 1 is Rest
Level 2 is Restfull
Level 3 is Hateoas
You should find more informations inside some books or articles written by Martin Fowler
What I usually do is use "POST" for creating a new resource, and use "PUT" for updating an already existing resource.
For your second question, yes most API's use the same URL to do different things on the same resource. That could be because of security where you don't want to expose what you are doing in your URL's (/delete for example). Also, many frameworks generate an auto URL for a resource (Object Class), that is then differentiated on the request method. People just don't tend to use custom URL's for those.

How to check which type of access user has (Nodejs and mongodb)

I am creating an alarm tracking management system for the remote smart devices. Using nodejs and mongodb. The idea is like this when the device has the alarm I want that the user who has permission could see the alarm error (or history of errors) after he logs in. Let say I have three types of user, first type can track only one group of devices, second another group and third all devices. For the demo version I am thinking to create a user in my mongodb and add the array with the 3 types of devices group and assign true of false to each device group depending on the access urer have. I already have log in system, but I want some advise how to check if the user has access to group one then he can be redirected after login to particular route and etc. What I think create a function that checks somehow 'if(user nameOfgroup1 is true) then redirect to nameOfgroup1 view' but not sure how to write code for this condition. My user schema:
var userSchema = mongoose.Schema({
local: {
username: String,
password: String,
access:[{
nameOfgroup1: String,
available: Boolean
},
{
nameOfgroup2: String,
available: Boolean
},
{
nameOfgroup3: String,
available: Boolean
}]}});
It would be simpler to store an array of group IDs that the user should have access to. That way you'll be able to easily add more groups in the future and also checking for a given group would be easy.
For example, if the user's doc in the DB would be something like:
{ "username" : "name", "groups" : [ 0, 2 ] }
then it's easy to check which groups he has access to but also to check a specific group with:
function check(user, group) {
return user.groups.indexOf(group) > -1;
}
Also it's easy to search for users with access to a given group in the database:
db.users.find({groups:2});
Instead of numbers you can use names or ObjectIds or whatever is convenient for you.

Can I restrict Easy Search to only return published data?

I'm using matteodem's Easy Search package and have just discovered that instead of returning only published documents, the searches have access to the entire collection.
I've tested this by setting my publish function to return an empty array, and then checking that MyCollection.find().fetch() in the console correctly returns []. But searching MyCollection with Easy Search still returns all matching documents in the collection.
Is there any way to ensure that Easy Search only passes permitted data up to the client? I can't find anything in the documentation.
Easy Search is running the search on the server where it has universal access. According to the docs you can setup a default selector to filter the search by some criteria. In your case you can just copy the selector from your normal publication (the first parameter in your publication's find()) and set that as the default selector for Easy Search.
let index = new EasySearch.Index({
collection: someCollection,
fields: ['name'],
engine: new EasySearch.Minimongo({
sort: () => ['score'], // sort by score
selector: function (searchObject, options, aggregation) {
// selector contains the default mongo selector that Easy Search would use
let selector = this.defaultConfiguration().selector(searchObject, options, aggregation);
// modify the selector to only match documents created by the current user
selector.createdBy = this.userId || options.search.userId; // to run on both client and server
return selector;
}
})
});
From matteodem, the developer of Easy Search, I have a simple answer to my original question of how to ensure that only published data are returned by a search.
The easiest way is to use a client-side search engine such as Minimongo. This accesses data through your publications, so will see exactly the data that you have published, no more no less. No selector is needed.
Example code:
postsIndex = new EasySearch.Index({
collection: Posts,
fields: ['name', 'tags', 'created_by_username'],
defaultSearchOptions: {
limit: 6
},
engine: new EasySearch.Minimongo() // search only on the client, so only published documents are returned
});
Alternatively you could use a server-side search engine such as MongoDB. In this case you should add a selector to control what data are returned.
Unfortunately I haven't been able to get selectors working with MongoDB. You can't use Meteor.userId() because the code runs on both server and client, and when I try the recipe for this in the documentation, I see an error on the server. Using Michel Floyd's construction, options.search.userId exists but is null. If I find out how to do it, I'll update this answer for completeness.

How to get pull requests filter with owner using Github API

I just want to query the PRs from a specific user.
Do I need to use the head param? But how?
https://api.github.com/repos/org-a/repo-b/pulls?state=open&per_page=1&head=owner:user-c does not work.
API Refer: https://developer.github.com/v3/pulls/#list-pull-requests
Use the Search API and specify repo:REPO, author:USER and is:pr filters:
https://developer.github.com/v3/search/#search-issues-and-pull-requests
For example, here are the pull requests from rails/rails from aderyabin:
https://api.github.com/search/issues?q=is:pr+repo:rails/rails+author:aderyabin
Here is the GraphQL API syntax to query the pull requests in the repo rails/rails from the author aderyabin:
{
search(query: "is:pr author:aderyabin repo:rails/rails", type: ISSUE, first: 100) {
issueCount
edges {
node {
... on PullRequest {
title
createdAt
url
}
}
}
}
}
The PullRequest object docs lists the fields available to query.
It doesn't seem to be possible at the moment to filter a user's PR for a given repo (or a repo's PR for a given user), but the same result can be achieved with the search query above.

Resources