• 开源镜像
  • 开源沙龙
  • 媛宝
  • 猿帅
  • 注册
  • 登录
  • 息壤开源生活方式平台
  • 加入我们

开源日报

  • 2018年8月5日:开源日报第150期

    5 8 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《后台管理模版 Material Dashboard》传送门:GitHub链接

    推荐理由:这个项目实际上是在开发团队开发出 Material Kit 之后基于它发布的仪表盘模版,如果后台有需要的话可以考虑使用这个,不过感觉重点还是可以看看这个 Material Kit,这是一套美观的 UI 套件,在开发的时候肯定会有朋友需要这个的。

    Material Kit:https://www.creative-tim.com/product/material-kit


    今日推荐英文原文:《The 6 kinds of people in Computer Science and Engineering》作者:Joel Vilanilam Zachariah

    原文链接:https://medium.com/fossmec/the-6-kinds-of-people-in-computer-science-and-engineering-4e6dae122ecd

    推荐理由:介绍了计算机科学和工程中的六种人,以及对于这六种人,开源社区如何帮助他们提升自己。

    The 6 kinds of people in Computer Science and Engineering

    Computer Science and Engineering can mean different things to different people.

    For some it might be the subject to explore the beauty of algorithms while for another group it might be all about automating the boring stuff. No matter how you perceive it, your time in University is to refine and discover your potential in the field. Buzzwords such as Machine Learning and Blockchain are heavily heard about in recent times and you will find out that engineers today specialized in this field were once upon a time college students exploring options.

    So how is it they made it there, and how can you discover your true path?

    I have come to realize that there mainly exists six kinds of people in Computer Science and Engineering at Universities and we at FOSSMEC believe there lies potential for each kind of person in the world of open source. So sit tight as we take you through the path of realization, and compare to see where you lie.

    Disclaimer: Personal opinion can be biased and wrong. Feel free to comment your thoughts 🙂 Also this does not have to restrict only to CSE student, in fact, this is open to anyone open minded and eager to see wonders of Open Source.

    Type A

    They are good — let them discover their path

    These folks are at the top of the chain after having seen a lot and climbed to the pinnacle. With a lot of experience and achievements, they have insights about how to proceed and lead the way. They motivate and support their fellow beings, with enthusiasm and dynamism. Google the name and you will find their entire achievement gallery bright and amazing.

    Those in this category have probably seen it all and know how to get things done. We all have seen a type A person at some point in our lives, as speakers at conferences or as inspirational leaders who use their technical knowledge not to show dominion but to help you get better.

    Shoot any question, they will have at least a word or two to say about it. Chances are that companies would badly want their skills because the world deserves that caliber. Each person of this kind is unique in their own way, and you will find them brainstorm and be creative. Siraj Raval is a great example in my opinion, check out his awesomeness in his YouTube Channel and his famous #100DaysOfMLCode.

    Some of them probably have their own start-ups, because as how SKG said in his talk show, “the best talent is not available for hire”

    Reaching this level while being in college requires extensive dedication and hard work, which can take a few years, so not many would be found of this sort. But the ones who do exist shine bright and everyone else easily identifies.

    Type B

    They are good — let them gain followers

    These guys have gone the extra mile to find their defining path and specialize further to get better. Errors and mistakes keep happening, but this time recovery is faster. They can be found at events and competitions trying to find where they stand on a global platform. With a gathering audience, these guys will amaze and impress thousands of followers.

    Check their GitHub repository and over tons of stars will be there. Also, their progress chart will be blazing green of varying densities. Have a look at their laptops and you will find many stickers on it, from the various conferences and events that they attended. They probably have interned in the top notch companies and has a good sense of how the field works. At Hackathon’s, these guys steal the show with their innovative ideas and well thought out implementation. Experience speaks for itself, after all.

    Also beyond just development skills such as Machine Learning, they have a strong foundation on Algorithms and develop optimal solutions for common problems. This will keep them at a higher level compared to most of the others in the field, and can leverage this factor to shine bright in creativity.

    The only thing lacking is confidence in oneself to lead the way and show others how to explore the field. The growing admiration from public will in time take them to Type A category once they embrace the potential within to lead the way and take on greater responsibilities.

    Type C

    They started — Gaining consistency and experience

    So these folks are at the other end of the spectrum where they work solo and quite, below the radar and undetected by many. They started a couple of months ago and now are gaining consistency. StackOverFlow and Google search history will show an assortment of errors to find recovery solutions. What once started as a simple interest now is an intense passion for reaching the peak in that field.

    They can be spotted at corners of metro stations, or public parks on a bench quietly coding, away from the noisy world but very much engrossed into what they do. Is it an addiction? Maybe, but then passion can be contagious too. These guys attend technical clubs and listen to speakers to pick up points to improve themselves.

    Don’t be mistaken though, these guys are still exploring options and have not yet decided what exactly to focus sharp on. Hope in the next couple of months they discover what truly interests them, and maybe think of hobby projects that merge multiple domains to generate amazing ideas and solutions.

    What is left is to do more projects and participate in events to discover potential to think out of the box and find solutions. That comes with more experience and tinkering to find one’s forte. What these people need is technical support to find and discover methods that they never knew previously existed. Socializing and up-skilling is the key to cross this realm, to the Type B.

    Type D

    They started — hitting hurdles and roadblocks

    Good news! These guys have decided it is high time they explored the wondrous and curious world of coding.

    Bad news? Several and several errors with exponentially increasing learning curve to climb.

    These folks are the ones who have decided it is time to enter the game and made up the mind to take the first few baby steps. Having defeated the procrastination, these guys are ready to tinker, but are quite sensitive to varying results. At times the impostor syndrome may kick in when they hit road blocks that they spent hours trying to solve but mere few seconds when someone more experienced just glances at it.

    This is the hardest one of the categories, because failure comes almost everyday but success once in a blue moon. Putting it away may seem to be the easy way out, but the persistent ones reap benefits for their patience. What these people need is motivational support to stay optimistic and continue down their track to start seeing results and get better. In time, they will reach Type C.

    Type E

    Not yet started — still figuring things out

    Meet the vast majority of you readers, filtering through the vast assortment of options and not sure where to start. Or maybe out right jumping to the conclusion that they are not good enough to even try. Self doubt and the risk of failing hinders them from trying.

    What they need is someone to talk to and convince them that it is not too late, and that every master was once a student. Time is what takes to climb up the ladder, and one can realize that only if the first step is taken.

    Also even if they are ready, the Google searches and varying degree of Quora answers would confuse them to even make a decision of what to do. In such situations, all it takes is a leap of faith and to explore a domain whose final product piques your interest and leaves you intrigued enough to get your fingers messy trying to fiddle about and enjoy in the process.

    As hypocritical as this may seem, I consider myself to be of this category and take the stance to say that Web-Development via freeCodeCamp is a good starting point. Hope all goes smoothly so that I can reach at least Type C before I graduate from University.

    Type F

    On an entirely different track, a new path

    The sixth and final type, the ones who have their hearts fixed on a different trajectory. It may be anything, from music, art, marketing, civil service etc. It would be naive to think that everyone who learns Engineering become an Engineer. Sometimes people discover their inner call later on and switch tracks. Though many may initially frown upon that, in time people will accept and if you are great at what you do, you will be well appreciated!

    To put it in short, these people have an unwavering passion for another domain and that is commendable when compared to the confused folks of Type E. Everything has its time to shine.

    So how does Open Source guide all six?

    So to put it in perspective, these are the differentiating factors:

    1. The difference between A and B is the confidence level.

    2. The difference between B and C is experience.

    3. The difference between C and D is consistency rate.

    4. The difference between D and E is the risk of failing before trying.

    5. The difference between E and F is decision made to learn in the mind.

    For those who have reached E, the goal of your time in University should be to climb up all the way, at least to Type B. To make this happen there are mainly two steps:

    1. Reach out to the technical clubs in your locality and effectively participate in discussions, free of th fear of judgment.
    2. Make an effort to help a fellow being get better at coding by connecting her with the solution she needs.

    But setting just a track is barely half the work done, so here we present you the ways on how open source community can help each type get better.

    For Type E, there are websites like freeCodeCamp, an open source collaborative end result, that has a simple layout to ensure one can read up and be convinced of the success rate of the trajectory. Also reading from open source forums and discussions, one can understand the trajectory people took.

    For Type D, there are a lot of open sourced tutorials and lessons to refer and get better in coding at GitHub. Beginner friendly tasks are there that are oriented to help you learn how to be a part of the community and make your first few commits to the system. If you hit road blocks, chances are someone is more than ready to help you, but the question is would you reach out and ask? Open Source community has your back.

    For Type C, there are several open sourced projects to which one can contribute and make an impact in its overall progress. It might seem scary at times, but with consistency and dedication you can see how easy it is to find answers and get exposure to the real world out there, via the internet.

    For Type B, you need specialized tools and applications to facilitate and support in the development phase of the product. Open Sourced alternatives make the entire process easier, and you can read from open source blogs to stay updated with recent trends.

    For Type A, the world needs thought leaders and open source has a lot of opportunities for those of caliber to stand up and take the open source enthusiasm to their locality via local events such as mini-DebConf or Open Source challenges to bring out the best within peers and coders.

    So what about type F? Yes we have something in store for you folks too! Finding the right tools for your work requires developers who listen to you and understand your requirement. These are free and need not be paid for, a huge gain for many starting artist who cannot afford expensive complementary tools. A good example would be Krita, an open source alternative to many image editing tools.

    Open Source application developers also take the extra mile to listen to your requirements via the open source thread of comments, and come up with the updates to meet your requirements! Isn’t this better than suggesting improvements to other applications that take several more months before even acknowledging it?


    So no matter where you stand, take a minute to appreciate how one can discover their path up the ladder. Embrace the collective support of open source, to empower yourself to reach the skies.

    Together, Open Source can empower everyone to reach their best self!


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

  • 2018年8月4日:开源日报第149期

    4 8 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《暗黑破坏神 Devilution》传送门:GitHub链接

    推荐理由:GitHub 上面什么都有的完美例证,这次居然可以看到暗黑破坏神……的源代码,暗黑破坏神是暴雪公司很久以前的一款游戏,现在已经停止维护了。对暗黑破坏神感兴趣的朋友可能很愿意看到这个,不过这个仅仅只是一代的暗黑破坏神,兴许它以后可以获得一些新的发展,比如更好的 UI 之类的,但是……它终究只是一代,偶尔回去看看,估计就差不多了。


    今日推荐英文原文:《JavaScript Weekly: Making Sense of Closures》作者:Severin Perez

    原文链接:https://medium.com/launch-school/javascript-weekly-making-sense-of-closures-daa2e0b56f88

    推荐理由:介绍了在 JavaScript 中什么是闭包和为什么要使用闭包。

    JavaScript Weekly: Making Sense of Closures

    One of the most powerful features of JavaScript is the concept of closure. It is this feature that lets us do things like create private data and define application interfaces. However, for new JavaScript programmers, the idea of closures, and how to use them, can be a bit confusing. Closure, as a concept, is closely tied to the idea of scope. JavaScript is lexically-scoped (meaning the scope is defined lexically, in the source code), which might make you think that it should be easy to reason about which variables are accessible where. But in truth, doing so does take some practice. And when you throw closure into the mix, it only gets harder. So, today we’re going to talk a bit about closure, and hopefully by the time we’re done you’ll find it a bit easier to understand what closure is and why we use it.


    A Brief Review of Scope

    Before we get started with closure, we should do a brief review of scope — the two concepts are, after all, inextricably intertwined. For an in depth look at scope, you can check out this article. The short version is as follows. Scope is composed of a set of nested boundaries that define which variables are accessible at any given point in your code. The top layer of scope is global scope and is universally accessible. Nested within global scope are individual layers of local scope or function scope. When your program attempts to look up the value held in a given variable, it starts at the closest level of scope (often inside a function), and if no such variable exists there, it then moves up to higher levels of scope, checking each one in turn. Note that this is a unidirectional process — higher levels are scope are accessible to lower levels, but not vice versa. Per usual, this is probably easiest to see in code:

    var event = "Coffee with Ada.";
    
    function calendar() {
      var event = "Party at Charles' house.";
      
      console.log(event);
    }
    
    calendar();               // Logs: "Party at Charles' house."
    
    console.log(event); // Logs: "Coffee with Ada."

    Here we have a variable in global scope called event, which holds the value “Coffee with Ada.” We also have a function called calendar, which contains a variable that is also called event but has the value “Party at Charles’ house.” When we call the function calendar, and it goes looking for a variable called event to log to the console, it finds the variable of that name that is defined in local scope. However, when we attempt to log the value of event from outside of any functions, it finds the variable of that name defined in global scope instead.


    Simple Closure

    Now that we have refreshed our understanding of scope, let’s look at closure. We know that variables are accessible depending on where they are in scope, but what does that mean for our function calls? Well, when you define a function it closes over the currently accessible scope and retains access to the variables defined in that scope. So, if you define a function in global scope, it has access to all of the variables in global scope, but nothing else. On the other hand, if you define a function inside another function (that is, in function scope), then it will have access to the variables in function scope and in global scope. This is where things can get tricky though. Let’s look at an example.

    var event = "Coffee with Ada.";
    
    function describeEvent() {
      console.log(event);
    }
    
    function calendar() {
      var event = "Party at Charles' house.";
      
      describeEvent();
    }
    
    calendar(); // Logs: "Coffee with Ada."

    In this snippet we have a global scope variable called event, a function defined in global scope called describeEvent, which simply logs the value of event, as it knows it. We also have another function called calendar that defines its own event variable in function scope and then calls describeEvent. So what then happens when we call the function calendar? You might expect it to log “Party at Charles’ house.”, which is the value of the event variable inside calendar’s function scope. However, the actual output is “Coffee with Ada.” The reason is that our describeEvent function had already closed over the variable event in global scope. It doesn’t matter that we’re calling describeEvent from inside calendar. As far as describeEvent is concerned, the event variable inside calendar doesn’t exist. And that’s closure in action!


    Closure in Higher-Order Functions

    Knowing why a particular function accesses a particular variable is great, but knowing how to leverage that power is even better. The primary way that we can use closure is by using higher-order functions. Remember, functions in Javascript are first-class objects, meaning that they can either accept a function as a parameter or be returned by another function. A higher-order function is one that takes advantage of these attributes. For our purposes, we’re mostly concerned a function’s ability to return another function, because if our higher-order function returns a function, then the function that we’re returning will close over any variables defined in the higher-order function’s scope. Consider the following.

    function makeEventDescriber(event, date) {
      return function() {
        console.log(date + ": " + event);
      };
    }
    
    var coffeeWithAda = makeEventDescriber("Coffee with Ada.", "8/1/2018");
    var partyAtCharles = makeEventDescriber("Party at Charles' house.", "8/4/2018");
    
    coffeeWithAda();          // Logs: "8/1/2018: Coffee with Ada."
    partyAtCharles(); // Logs: "8/4/2018: Party at Charles' house."

    This example defines a function called makeEventDescriber, which accepts an event and a date string as parameters. On being called, the function assigns the provided values to local scope variables named event and date. It then returns another function, which closes over those variables and uses them to log a value to the console. After defining this function, we then use it to make two new functions called coffeeWithAda and partyAtCharles respectively.

    Now that we have two new functions, coffeeWithAda and partyAtCharles, what happens when we call them? Note that neither of them accepts any parameters, and yet, when we call them they output the strings that we expect. So how do they retain access to the date and event variables that they depend upon to function properly? And how is it that they have different values? All of this happens because of closure. The functions returned by makeEventDescriber have closed over the values provided to it when it was called, which is why coffeeWithAda and partyAtCharles have access to different values.


    Fun with Partial Function Application

    One of the neat things about closure is that it lets us create functions that have pre-applied parameters. This is called partial function application, and we can use it to make functions that make other functions. For example, what if we knew that we wanted to schedule lots of events with our friend Ada. Wouldn’t it be nice to not have to provide the name “Ada” to every event that we schedule with her? We can do exactly that with partial function application.

    function schedulerMaker(name) {
      return function(event) {
        return function() {
          console.log(event + " with " + name + ".");
        };
      };
    }
    
    var adaScheduler = schedulerMaker("Ada");
    var coffeeWithAda = adaScheduler("Coffee");
    
    coffeeWithAda(); // Logs: "Coffee with Ada."

    Here, we have a function called schedulerMaker, which has a single parameter that expects a name string. This function then returns another function, which accepts an event as its parameter. Finally, this function itself returns a final function, which when called, logs a string describing our event. That’s a lot of functions, so let’s try to follow what is happening.

    First, we call schedulerMaker with the argument “Ada” and it gives us a new function, which we assign to the variable adaScheduler. For its part, adaScheduler closes over the variable name, which contains the value of “Ada”, and therefore retains permanent access to it. We then call adaScheduler with the argument “Coffee”, which it assigns to the variable event, and it in turn returns another function that is going to describe our event. Now, we have a function called coffeeWithAda that has, in effect, closed over two levels of scope, thus giving it access to both the event and name variables. And indeed, when we call coffeeWithAda, the message “Coffee with Ada” is logged to the console.

    Keep in mind that the event and name variables we are using here are not universal. If we wanted, we could use schedulerMaker to create many more functions, each with a different name attached. We could then in turn use those functions to create many more event describers, and each one would have access to different values.


    Private Data and Application Interfaces

    Two of the biggest benefits of closure are the ability to create private data and to define application interfaces. Sometimes, you want to enforce the way in which a program interacts with data so that you can protect its integrity. By using closure, you can do exactly this. One common way of creating such an interface is by returning an object from a function. Methods defined on this object, just like any other functions, close over the current scope. This means that we can define private data inside the overall function scope, which will only be accessible to methods defined on our object. Here is an example:

    function makeCalendar(name) {
      var calendar = {
        owner: name,
        events: [],
      };
      
      return {
        addEvent: function(event, dateString) {
          var eventInfo = {
            event: event,
            date: new Date(dateString),
          };
          calendar.events.push(eventInfo);
          calendar.events.sort(function(a, b) {
            return a.date - b.date;
          });
        },
        
        listEvents: function() {
          if (calendar.events.length > 0) {
            console.log(calendar.owner + "'s events are: ");
            
            calendar.events.forEach(function(eventInfo) {
              var dateStr = eventInfo.date.toLocaleDateString();
              var description = dateStr + ": " + eventInfo.event;
              
              console.log(description);
            });
          } else {
            console.log(calendar.owner + " has no events.");
          }
        },
      };
    }
    
    var babbageCalendar = makeCalendar("Charles Babbage");
    
    babbageCalendar.addEvent("Coffee with Ada.", "8/7/2018");
    babbageCalendar.addEvent("Difference Engine presentation.", "8/2/2018");
    
    babbageCalendar.listEvents();
      /*
        Logs:
        Charles Babbage's events are: 
        8/2/2018: Difference Engine presentation.
        8/7/2018: Coffee with Ada.
      */

    In this mini-program we have a function called makeCalendar which accepts a single parameter (a name of the calendar owner) and returns an object. This object has several methods defined on it to add and list calendar events. These methods, through closure, have access to a private calendar object that is defined in the overall function scope. This object is only accessible to those methods and not to the program as a whole. We see this in action at the bottom of the snippet where we create and interact with an object called babbageCalendar.

    What is interesting about this pattern is that the calendar object that babbageCalendar is interacting with is completely private. There is no way to directly manipulate the calendar.events array or the calendar.owner string — we can only do so by using the explicitly defined interface that is returned by makeCalendar. This can be very powerful, but it has downsides as well. What if we wanted a way to change the date on a particular event? Well, we can only do that by going back to the original code and adding a changeDate method to the interface. As a result, this pattern is not particularly easy to extend, but for our purposes, it illustrates the power of closure.


    TL;DR

    In JavaScript, the concept of closure is closely tied to the concept of scope. Closure happens when you define a function, which then closes over all of the variables accessible to it in the current scope. Once a function is defined, it will retain access to those variables regardless of where it is called. This is useful behavior because it allows us to create functions that have access to private data. By doing this, we can leverage higher-order functions, partial function application, and private application interfaces.


    And that’s all for today’s exploration of closure! Hopefully this has been a useful review of how closure works and how you can use it effectively. As always, happy coding!


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

  • 2018年8月3日:开源日报第148期

    3 8 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《你说人话我也听得懂 NLP-progress》传送门:GitHub链接

    推荐理由:NLP,全称自然语言处理,是人工智能里面关于让机器听懂人话的那个方面。这个项目就记录了当前 NLP 的发展程度,比如词性标注,阅读理解和推理等等。如果你对如何让计算机读懂人话感兴趣的话,不妨来这里看一看。


    今日推荐英文原文:《An Introduction to GraphQL》作者:Flavio Copes

    原文链接:https://hackernoon.com/an-introduction-to-graphql-2c3f7d8fb4e0

    推荐理由:介绍了 GraphQL,最近工场内也有简单介绍 GraphQL 的文章,想看看的话可以点击这个链接(传送门)。

    An Introduction to GraphQL

    GraphQL is the new frontier in APIs (Application Programming Interfaces).

    It’s a query language for your API, and a set of server-side runtimes (implemented in various backend languages) for executing queries.

    It’s not tied to a specific technology, but you can implement it in any language.

    It is a methodology that directly competes with REST (Representational state transfer) APIs, much like REST competed with SOAP at first.

    GraphQL was developed at Facebook, like many of the technologies that are shaking the world lately, like React and React Native, and it was publicly launched in 2015 — although Facebook used it internally for a few years before.

    Many big companies are adopting GraphQL beside Facebook, including GitHub, Pinterest, Twitter, Sky, The New York Times, Shopify, Yelp and thousands many other.

    GraphQL Principles

    GraphQL exposes a single endpoint.

    You send a query to that endpoint by using a special Query Language syntax. That query is just a string.

    The server responds to a query by providing a JSON object.

    Let’s see a first example of such a query. This query gets the name of a person with id=1:

    GET /graphql?query={ person(id: "1") { name } }

    or simply

    { person(id: "1") { name } }

    We’ll get this JSON response back:

    { "name": "Tony" }

    Let’s add a bit more complexity: we get the name of the person, and the city where the person lives, by extracting it from the address object. We don’t care about other details of the address, and the server does not return them back to us.

    GET /graphql?query={ person(id: "1") { name, address { city } } }

    or

    { 
      person(id: "1") { 
        name 
        address { 
          city 
        } 
      } 
    }
    { 
      "name": "Tony", 
      "address": { 
        "city": "York" 
      } 
    }

    As you can see the data we get is basically the same request we sent, filled with values.

    GraphQL vs REST

    Since REST is such a popular, or I can say universal, approach to building APIs, it’s fair to assume you are familiar with it, so let’s see the differences between GraphQL and REST.

    Rest is a concept

    REST is a de-facto architecture standard but it actually has no specification and tons of unofficial definitions. GraphQL has a specification draft, and it’s a Query Language instead of an architecture, with a well defined set of tools built around it (and a flourishing ecosystem).

    While REST is built on top of an existing architecture, which in the most common scenarios is HTTP, GraphQL is building its own set of conventions. Which can be an advantage point or not, since REST benefits for free by caching on the HTTP layer.

    A single endpoint

    GraphQL has only one endpoint, where you send all your queries. With a REST approach, you create multiple endpoints and use HTTP verbs to distinguish read actions (GET) and write actions (POST, PUT, DELETE). GraphQL does not use HTTP verbs to determine the request type.

    Tailored to your needs

    With REST, you generally cannot choose what the server returns back to you, unless the server implements partial responses using sparse fieldsets, and clients use that feature. The API maintainer cannot enforce such filtering.

    The API will usually return you much more information than what you need, unless you control the API server as well, and you tailor your responses for each different request.

    With GraphQL you explicitly request just the information you need, you don’t “opt out” from the full response default, but it’s mandatory to pick the fields you want.

    This helps saving resources on the server, since you most probably need less processing, and also network savings, since the payload to transfer is smaller.

    GraphQL makes it easy to monitor for fields usage

    With REST, unless forcing sparse fieldsets, there is no way to determine if a field is used by clients, so when it comes to refactoring or deprecating, it’s impossible to determine actual usage.

    GraphQL makes it possible to track which fields are used by clients.

    Access nested data resources

    GraphQL allows to generate a lot less network calls.

    Let’s do an example: you need to access the names of the friends of a person. If your REST API exposes a /person endpoint, which returns a person object with a list of friends, you generally first get the person information by doing GET /person/1, which contains a list of ID of its friends.

    Unless the list of friends of a person already contains the friend name, with 100 friends you’d need to do 101 HTTP requests to the /person endpoint, which is a huge time cost, and also a resource intensive operation.

    With GraphQL, you need only one request, which asks for the names of the friends of a person.

    Types

    A REST API is based on JSON which cannot provide type control. GraphQL has a Type System.

    Which one is better?

    Organizations around the world are questioning their API technology choices and they are trying to find out if migrating from REST to GraphQL is best for their needs.

    GraphQL is a perfect fit when you need to expose complex data representations, and when clients might need only a subset of the data, or they regularly perform nested queries to get the data they need.

    As with programming languages, there is no single winner, it all depends on your needs.

    GraphQL Queries

    In this article you’ll learn how is a GraphQL query composed.

    The concepts I’ll introduce are

    • fields and arguments
    • aliases
    • fragments

    Fields and arguments

    Take this simple GraphQL query:

    { 
      person(id: "1") { 
        name 
      } 
    }

    In this query you see 2 fields, and 1 argument.

    The field person returns an Object which has another field in it, a String.

    The argument allows us to specify which person we want to reference. We pass an id, but we could as well pass a name argument, if the API we talk to has the option to find a person by name.

    Arguments are not limited to any particular field, we could have a friends field in person that lists the friends of that person, and it could have a limit argument, to specify how many we want the API to return:

    { 
      person(id: "1") { 
        name
        friends(limit: 100) 
      } 
    }

    Aliases

    You can ask the API to return a field with a different name, for example:

    { 
      owner: person(id: "1") { 
        fullname: name 
      } 
    }

    will return

    { 
      "data": {
        "owner": { 
          "fullname": "Tony" 
        } 
      } 
    }

    This feature, beside creating more ad-hoc naming for your client code, is the only thing that can make the query work if you need to reference the same endpoint 2 times in the same query:

    { 
      owner: person(id: "1") { 
        fullname: name 
      } 
      first_employee: person(id: "2") { 
        fullname: name 
      } 
    }

    Fragments

    In the above query we replicated the person structure. Fragments allow us to specify the structure once (much useful with many fields):

    { 
      owner: person(id: "1") {
        ...personFields 
      } 
      first_employee: person(id: "2") {
        ...personFields
      }
    } 
    fragment personFields on person {
      fullname: name 
    }

    GraphQL Variables

    More complex GraphQL queries need to use variables, a way to dynamically specify a value that is used inside a query.

    In this case we added the person id as a string inside the query:

    { 
      owner: person(id: "1") { 
        fullname: name
      } 
    }

    The id will most probably change dynamically in our program, so we need a way to pass it, and not with string interpolation.

    With variables, the same query can be written as

    query GetOwner($id: String) { 
      owner: person(id: $id) { 
        fullname: name 
      } 
    } 
    { 
      "id": "1"
    }

    In this snippet we have assigned the GetOwner name to our query. Think of it as named functions, while before you had an anonymous function. Named queries are useful when you have lots of queries in your application.

    The query definition with the variables looks like a function definition, and it works in an equal way.

    Making variables required

    Appending a ! to the type:

    query GetOwner($id: String!)

    instead of $id: String will make the $id variable required.

    Specifying a default value for a variable

    You can specify a default value using this syntax:

    query GetOwner($id: String = "1")

    GraphQL Directives

    Directives let you include or exclude a field if a variable is true or false.

    query GetPerson($id: String, $getAddress: Boolean) { 
      person(id: $id) { 
        fullname: name, 
        address: @include(if: $getAddress) { 
          city 
          street 
          country 
        } 
      } 
    }
    { 
      "id": "1", 
      "getAddress": false
    }

    In this case if getAddress variable we pass is true, we also get the address field, otherwise not.

    We have 2 directives available: include, which we have just seen (includes if true), and skip, which is the opposite (skips if true)

    @include(if: Boolean)

    query GetPerson($id: String, $getAddress: Boolean) { 
      person(id: $id) { 
        fullname: name, 
        address: @include(if: $getAddress) { 
          city 
          street 
          country 
        } 
      } 
    } 
    {
      "id": "1", 
      "getAddress": false 
    }

    @skip(if: Boolean)

    query GetPerson($id: String, $excludeAddress: Boolean) { 
      person(id: $id) { 
        fullname: name, 
        address: @skip(if: $excludeAddress) { 
          city 
          street 
          country 
        } 
      } 
    }
    { 
      "id": "1", 
      "excludeAddress": false 
    }

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

  • 2018年8月2日:开源日报第147期

    2 8 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《从零开始的 React 新手教程 React From Zero》传送门:GitHub链接

    推荐理由:这个项目是 React 的新手教程,从 React 的基础元素开始讲起,到组件和它们的属性,再到重构,引用与库的整合。教程中还有示例代码,如果想要学习 React 的话,看一看这个新手教程兴许会对你有所帮助。


    今日推荐英文原文:《How to get better at writing CSS》作者:Charlotte Davies

    原文链接:https://medium.com/@charlotte.davies/where-can-you-work-if-you-code-a642fced215b

    推荐理由:如果你学会了编程,你想去哪里工作呢?作者用自己的经验为我们分析了去不同类型的公司工作的优缺点

    Where can you work if you code?

    This week, a number of conversations have been around what kind of opportunities there are available to new developers, once you have learnt to code.

    From applying for jobs post-bootcamp myself, broadly they fit into these 3 categories: Startups, Agencies and Established Companies.

    Please take what I say here with a pinch of salt. It is opinion based and only what I have found from my experience.

    My advice would be to:

    1. Throughly research the company before you go and work there.
    2. Talk to as many people as you can about their experiences.
    3. Make up your own mind on what suits you, your personality and your skillset.

    Startups

    This is probably what initially springs to mind when you think tech. Someone über cool, sat in a garage, plugged into a laptop, changing the world one line of code at a time.

    I interviewed for a number of startup roles, from craft beer startups, to finance and travel. I think the exciting thing about working within tech is that you can work in literally any industry and you don’t initially need to know much about the industry (although you certainly absorb a fair amount on the job). Currently I’m working on a project for the Automobile industry and now I know a lot more about cars than I ever thought I would, simply through arranging the content in my code. During my job hunt, I applied for a lot of opportunities within the fashion industry — an industry that usually requires oodles of internships, experience and in some cases a degree to get inside. Coding feels like sneaking in the back door to your dream company.

    Working within a start up environment can be super exciting.

    The pros:

    1. The variety of projects you might work on — everyday will likely be different and you can gain experience in a lot of different areas.
    2. The fact that you are working to create something original may lead you to try new things that perhaps you might not otherwise have worked on. You could be lucky and work on the next Google. Equally you could be out of a job within the year, but it will 100% be brilliant experience.
    3. You can learn a lot fast because the typically low-budget under-resourced nature of startups requires everyone to be really hands on with all projects.

    The cons:

    1. You might not get the level of training and support that you may receive in a more established company. There are unlikely to be training schemes available and your colleagues may be too busy to offer much guidance.
    2. It is often incredibly fast paced. This can be intimidating, or exciting depending on how you look at it. Either way, you are likely to be looking at pretty long hours.

    Agencies

    Your golden ticket is that not many people can code. I mean lots of people can code, but proportional to demand it’s not that many. Companies pay agencies handsomely for your skills.

    Agencies tend to be either digital agencies or marketing agencies and you could be building anything from simple websites and banner ads, to email bulletins to and complex new apps. Day to day, you will probably be building designs created by a UX/creative design team. You may even have the opportunity to suggest new features for the client. You also have the opportunity to work freelance or as a contractor — more money available but less job-security and not ideal for beginners as you lose out on mentorship and training at work. You could work anywhere in the World though so great for anyone who needs flexibility in their work, or even just for those that fancy being able to work anywhere in the World — coding on the beach anyone?!

    You can choose to work in any kind of field as agencies tend to specialise in a certain sector. Personally I love the luxury industry as it requires a sharp attention to detail that I love to be able to offer a client. You can also use your other skills and previous professional knowledge to excel within agencies so it can be a great environment for a career changer.

    The pros of working in agencies are:

    1. A variety of projects and tech stacks to work on — it’s a great place to get exposure early on in your career to a number of different stacks.
    2. Working for some big name clients and often the chance to see your work in some exciting places (although you may be bound by client confidentiality and not allowed to tell your friends).
    3. Often more support than in startups as there tends to be more people around to mentor you and invest in your long term development.

    The cons might be:

    1. The work can be a bit samey and limiting to what you build as you are often have to work very closely to the client’s brief — often you can find yourself implementing simple HTML, CSS and JavaScript before you can take on some more ambitious projects.

    Established companies

    I’m a little biased as I work for one of the biggest consultancies in the World.

    In general, for the established companies I interviewed for, the benefits are:

    1. The support, job security, training, mentorship. Big companies have a lot more time and money to spend on your development. You will also likely work in a bigger team who can support you. As the company has grown, they will likely be used to supporting the development of junior devs so many will already have some kind of training and development programme in place.
    2. The benefits and job-security tend to be better in a bigger company.

    The cons are sometimes:

    1. Having less responsibility and less interesting work thrown at you initially. Though it is worth adding that you will likely get more responsibility quicker if you ask for it and prove that you can handle it. See my previous blog on how to keep up.
    2. Often working a lot with legacy code can be frustrating and you might not be able to move the tech on as fast because bureaucracy and complexities of the existing code base.

    I feel I have really landed on my feet at DV as it kind of fits into all 3. The fun of a start up but with proper training and job security. We are owned by The Boston Consulting Group so the support, training and benefits are truly fantastic, but we are also well shielded from corporate bureaucracy by our brilliant partners and directors! We have the variety and big name clients of an agency with the real opportunity to work with and learn about new technology. For example I didn’t know what IOT was before I started here. Hearing about it in a couple of Engineering meetings, I Googled and now once I’ve mastered the coding basics I’d not only be really keen to start working on some IoT projects but DV may well one day offer one of those opportunities. (FYI, IoT is “the internet of things” — basically computers talking to computers — think sensors, wearable tech and voice/image recognition apps — to receive more detailed and accurate data which can be used to reduce the necessary human interaction and improve efficiency.) Plug over! (But do get in touch if you want to hear more!)


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

←上一页
1 … 222 223 224 225 226 … 262
下一页→

Proudly powered by WordPress