What is gatsbyContentfulFluid? - javascript

I'm learning Gatsby and GraphQL as a newbie and following this article
https://ibaslogic.com/gatsby-with-contentful-cms/
It has this code:
export const query = graphql`
query($slug: String!) {
contentfulBlogPost(slug: { eq: $slug }) {
title
publishedDate(formatString: "Do MMMM, YYYY")
featuredImage {
fluid(maxWidth: 750) {
...GatsbyContentfulFluid
}
}
}
}
`
I'm getting everything but not getting ...GatsbyContentfulFluid on my GraphQL query server.
C
an someone please explain what ...GatsbyContentfulFluid is?
Why we are using it with a spread operator?
and did I miss something while creating Contentful data that's why I'm not getting ...GatsbyContentfulFluid in my GQL query playground?

It's not a spread operator like we know it in JavaScript, in GraphQL stands for a query fragment.
A fragment's a way of querying a set of fields using reusable units. From GraphQL docs:
Let's say we had a relatively complicated page in our app, which lets
us look at two heroes side by side, along with their friends. You can
imagine that such a query could quickly get complicated, because we
would need to repeat the fields at least once - one for each side of
the comparison.
That's why GraphQL includes reusable units called fragments. Fragments
let you construct sets of fields, and then include them in queries
where you need to. Here's an example of how you could solve the above
situation using fragments:
In your case, the fragment is provided by gatsby-source-contentful and basically, is querying a fluid asset from Contentful, as you do normally when using gatsby-image for local files.
In other words, with ...GatsbyContentfulFluid fragment you are fetching the mandatory fields from Contentful assets that allow you to use a gatsby-image within the asset.
Fragments are not available in the GraphQL playground due to a limitation of the GraphiQL:
Note, due to a limitation of GraphiQL, you can not currently use these
fragments in the GraphiQL IDE.
So, you can use fragments (indeed, you should) but you will need to check your fetched data in your code (via console.logs or via debug breakpoints) directly since they are not available in the GraphQL playground.

Related

Recursive RESTAPI Query

For some background, I have a number of enterprise systems management products that run a REST API called Redfish. I can visit the root folder on one such device by going here:
https://ip.of.device/redfish/v1
If I browse the raw JSON from a GET request, the output includes JSON data that look like this. I'm truncating this due to how long it is, so perhaps some JSON syntax errors here.
{
Description: "Data",
AccountService: {
#odata.id: "/redfish/v1/AccountService"
},
CertificateService: {
#odata.id: "/redfish/v1/CertificateService"
}
}
Perhaps in my searching I'm using the wrong terminology, but each of those #odata.id items is basically a 'folder' I can navigate into. Each folder has additional data values, but still more folders. I can capture contents of folders I know about via javascript and parse the JSON simple enough, but there are hundreds of folders here, some multiple layers deep and from one device to the next, sometimes the folders are different.
Due to the size and dynamic nature of this data, is there a way to either recursively query this from an API itself or recursively 'scrape' an API's #odata.id 'folder' structure like this using Javascript? I'm tempted to write a bunch of nested queries in foreach loops, but there's surely a better way to accomplish this.
My eventual goal is to perform this from nodejs, parse the data, then present the data in a web form for a user to select what fields to keep, which we'll store for faster lookups in a mongodb database along with the path to the original data for more targeted api queries later.
Thanks in advance for any suggestions.

Typescript and REST API response

Let me preface this question by saying that I am fairly new to typescript, but a long time JavaScript developer.
I have an existing JavaScript application that I am looking to transition over to typescript. In the JavaScript app, it makes a rest API call to fetch data, then checks to see if it exists, and then conditionally renders the app. In JavaScript, I can dynamically check to see if Properties exist on the response object and conditionally render that. In typescript, it throws an error because the data is of any type, and it doesn’t know if that property exists or not.
In a typescript application, is it pretty common to go create types for all of your API responses, so that you can get type safety on them? Using node as your backend, I could see a huge opportunity where you might be able to share backend and front end models. I am currently using .net core for my backend, and I am concerned I might be shooting myself in the foot trying to always create typescript models from the entity framework models.
Does anyone else use .net core for the backend and react on the front end? How do you handle API responses in typescript?
I can't tell you if it's common, but we write json-schema files for every endpoint. These schema files are:
Used to validate request bodies and generate errors.
Used to generate documentation.
Converted in to typescript types, which are used in both front- and backend.
We are using the same stack as you--.Net Core backend/React frontend--with typescript. The way we handle it is by creating types for the objects the backend sends us and then converting the dynamic checkers, like the ones you mention, into user-defined type guards.
So, roughly speaking, for the various data transfer objects the server returns we have a type/type guard pair that looks like this:
// type
export type SomeDto = { someKey: string; someOtherKey: number }
// type guard
export const isSomeDto = (returnedObj: any): returnedObj is SomeDto =>
returnedObject.someKey && typeof returnedObj === "string"
returnedObject.someOtherKey && tyepeof returnedObj === "number"
Then we have basically have the following in the fetching code:
const someReturn = fetchDatafromApi(endpoint)
if isSomeDto(someReturn) {
//now typescript will recognize someReturn as SomeDto
} else {
// throw or otherwise handle the fact you have bad data from the
// server
}
This way you get the dynamic checking in javascript at runtime and type safety at compile time. These guards aren't super-fun to write (and you'll want to unit test them all), and I imagine if the possible number of objects was bigger we'd opt for a more automated solution like #Evert mentions in the other answer. But for a few objects, and existing javascript validators, it is a pretty convenient way to get typing on your API returns.

Strongly typed GraphQL queries

I'm setting up a project with Vue CLI, using axios as my request library. All of the examples that I've seen uses a string as the query, e.g.
{
hero {
name
friends {
name
}
}
}
Since I'm using typescript and have typings for the entities, is there any way to generate the query using some kind of fluent framework or similar, so that I can work with intellisense instead of plain strings?
Most clients require you to provide the query as a string. You can use an IDE like GraphiQL, GraphQL Playground or Altair to provide features like autocompletion and syntax highlighting when writing your query. Certain editors also have plugins that offer similar functionality. If you're using TypeScript, you can typically use something like GraphQL Code Generator or Apollo CLI to then generate the types based on your queries and your schema.
The only client I'm aware of that is generated from your schema, allowing you to use a fluent API instead, is GraphQL Zeus.

How to generate HTML with javascript on the server side (Node.js)?

I am trying to validate the user input from a register form, basically one of those forms when you create an account (signup), since after some research, people recommend to validate on both client side and server side to improve security.
Objective:
What I would like to achieve is when the user submits the form, therefore making a POST request to my server (the url can be /users/signup), the input will be validated with the use of express-validator. This way I can verify if the user specified a valid email, if the password and its confirmation match, etc, and if there are errors, I want to update the html page by adding a list of errors.
Note that I'd prefer to only update the necessary parts instead of the whole page to remove redundant rendering.
Now I know that I can use a template engine like Jade or Handlebars, which would result in code similar to this: res.render('signup', {errors: errors.array()}); where errors is a variable containing the validation result, and then the signup file with the code of the particular templating engine. But I would like to know if there are other ways of achieving the same without learning a new template engine, maybe similar to what JSX code looks like.
Here is the code I propose that uses a module with the necessary implementation (its not completed):
let express = require("express");
const html = require("../htmlGenerator/html");
const { check, validationResult } = require("express-validator/check");
let router = express.Router();
/* Create a new account/user. */
router.post("/signup", [
// Input Validation.
check("email", "Email is not valid").isEmail()
// ...
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty())
res.send(htmlErrorList(errors.array()));
//...
});
function htmlErrorList(errors) {
return html.ul(
errors.reduce((res, error) =>
res + html.li({class: "alert alert-danger"}, error.msg), "")
);
}
The idea of these functions, ul() and li(), is to create the HTML string with the given attributes (represented by an object with the properties being the attribute name and then its according value) and the content inside the tag we are creating.
The benefits I see with making or using a module that allows this sort of use are:
It promotes functional style coding
We don't need to learn a new template language to achieve something we can do with javascript
We can use the full power and capabilities of the javascript language, for example make a function that produces the HTML code of the navbar used in all end-points of the app.
Final notes:
I know that many times we want to access a database or any other data source, on the server, and pull some data to make complex computations in order to format it and display in a way the user understands. One of the solutions is, again the use of a template engine, and I'd like to know if the idea I suggest is valid and if there are any other solutions to this problem.
I appreciate any help or feedback on this subject.
This question is kind of "opinion" based so i will give my opinion.
1) Use a templating engine. It makes your life a lot easier.
2) Templating engines are easy to use. You can learn to use most them in half an hour. Making your own code would require a lot more time than just using an already proven method. Plus, other developers can easily read and edit the code if it's written using common tools whereas they would have to spend the time to learn whatever custom solution you have come up with.
3) Your example is so simple that you could generate that "HTML" just by concatenating strings and using template literals. If your example gets more complicated...than your solution would become much ... much harder to read and maintain.
4) You don't really need to "output" HTML for errors at all. Just output a JSON object and have the frontend handle it. e.g
res.send({errors: [{field: 'username', message: 'username is required'}, ...]});
5) You don't really need to output HTML for anything...other than the first page of your app/site. Keywords here are webpack + angular 2(angular is the "A" in MEAN stack).
It is used for a reason...it works and its good.
So, in summary, I would say, unless you have a really good reason to avoid template engines, I would go with a template engine.

Is it possible to use Graphql generated schema as Flow definitions?

I have a project that uses the convo GraphQL, Relay and Flow. Is there a way to use GraphQL schema to feed Flow so the React props can be typed without redeclaring the types?
For Relay I'm already using the script that generates two files: schema.json and schema.graphql. The Babel plugin uses schema.json to translate the queries into javascript.
The other file, schema.graphql looks similar to Flow syntax definition for types, but there are differences. I've tried once to import type {Definition} from "./schema.graphql" from it but was failing silently.
The problem with that is GraphQL scalar-types can be used to represent values in various formats and they do not inherit from a base type you could fall back to for flow.
Scalar can not only verify a "string" but "string of 32 hexadecimal digits". It's not possible to declare this kind of type in flow.
Here are some alternatives: babel-plugin-typecheck, json-to-flow
So after a while I decided to tackle this since our project started to grow and we started to loosen our types. In the end the simplest solution has been to grab the printerSchema and modify it so it outputs flow friendly text, save it to a .js file and point libraries to there.
I'll try to post it in github in a later date

Categories

Resources