MERN Stack & GraphQL - #2 Express GraphQL Server
GraphQL.js allows for a GraphQL integration with Node.js, but it's only one piece of a puzzle. Many web apps in Node are built with a framework, such as Express. To host a GraphQL API service on an Express web server, we would need to pull in another dependency known as express-graphql (https://github.com/graphql/express-graphql). It exposes an HTTP middleware that allows to mount a GraphQL server to an endpoint. As a side note, you could also use express-graphql with Restify as well.
Just like before, we'll define our schema using GraphQL SDL and write out resolver functions in the rootValue object. For development, we'll also enable GraphiQL, which is a handy browser tool for interacting with GraphQL. As you're going to see, a GraphQL query is nothing but a POST (in Apollo Server, a POST or a GET) request to /graphql endpoint, where the body payload contains the JSON formatted query string with optional variables. The response from the GraphQL web service is a JSON object containing the "data" key, as well as a data structure mirroring the user requested query.
You could easily issue a query with a curl command, or even an AJAX request, using the native fetch API or a 3rd party lib, like axios. In fact, GraphQL clients, including urql, Apollo Client, or Relay, work exactly by that principle, though they often offer extra functionality on top, such as caching or state management.
As good as it is, express-graphql is not very flexible with composite types. Most apps have intertwined relationships between resources; for instance, in a blog site, users have posts, posts have comments, and comments have likes, etc. Unless you can rely on a perfect 1 to 1 mapping with your ORM, if it allows for it, your only options are to
- default back to the verbose (and IMO, messy) object-based approach (https://graphql.org/graphql-js/constructing-types) where it's easy to mix up your schema with the business logic, or
- stick with the GraphQL SDL and root level resolvers, but wrap your data entities with ES6 model classes, where you define getter methods for custom properties and relationships.
The latter can certainly work, but there's a better game in town. We'll explore a more modularized and cleaner approach next. Stay tuned!
GraphQL SDL—Schema Definition Language https://blog.graph.cool/graphql-sdl-schema-definition-language-6755bcb9ce51
Running an Express GraphQL Server https://graphql.org/graphql-js/running-an-express-graphql-server
graphqlHTTP middleware options https://github.com/graphql/express-graphql#options
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «MERN Stack & GraphQL - #2 Express GraphQL Server», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.