-
Notifications
You must be signed in to change notification settings - Fork 1
docs: add Spanish README #150
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
|
|
||
|
|
||
| [![NPM Status][npm-image]][npm-url] | ||
| [![GitHub license][license-image]][license-url] | ||
| [![LGTM Status][lgtm-image]][lgtm-url] | ||
| [](https://www.codacy.com/manual/subash.adhikari/nextjs-with-apollo) | ||
| [](https://img.shields.io/david/adikari/nextjs-with-apollo) | ||
|
|
||
| # ⚓ nextjs-with-apollo | ||
| HOC de Apollo para NextJS. | ||
|
|
||
|
|
||
| ## Instalación | ||
|
|
||
| Instala el paquete con npm | ||
|
|
||
| ```sh | ||
| npm install nextjs-with-apollo | ||
| ``` | ||
|
|
||
| o con yarn | ||
|
|
||
| ```sh | ||
| yarn add nextjs-with-apollo | ||
| ``` | ||
|
|
||
| ## Uso básico | ||
|
|
||
| 1. Crea un HOC | ||
|
|
||
| Crea el HOC utilizando una configuración básica. | ||
|
|
||
| ```js | ||
| // hocs/withApollo.js | ||
| import withApollo from 'nextjs-with-apollo'; | ||
| import ApolloClient from 'apollo-client'; | ||
| import { InMemoryCache } from 'apollo-cache-inmemory'; | ||
|
|
||
| const GRAPHQL_URL = 'https://your-graphql-url'; | ||
|
|
||
| const createApolloClient = ({ initialState, headers }) => | ||
| new ApolloClient({ | ||
| uri: GRAPHQL_URL, | ||
| cache: new InMemoryCache().restore(initialState || {}) // hydrate cache | ||
| }); | ||
|
|
||
| export default withApollo(createApolloClient); | ||
| ``` | ||
| Los parámetros `initialState` y `headers` se reciben en el hoc. | ||
|
|
||
| Si la renderización ocurre en el servidor, se puede acceder a todos los encabezados recibidos por el servidor a través de `headers`. | ||
| Si la renderización ocurre en el navegador, hidratamos la caché del cliente con el estado inicial creado en el servidor. | ||
|
|
||
| 1. Ahora usa el HOC | ||
|
|
||
| ```js | ||
| import React from 'react'; | ||
| import { useQuery } from '@apollo/react-hooks'; | ||
|
|
||
| import withApollo from 'hocs/withApollo'; | ||
|
|
||
| const QUERY = gql` | ||
| query Profile { | ||
| profile { | ||
| name | ||
| displayname | ||
| } | ||
| } | ||
| `; | ||
|
|
||
| const ProfilePage = () => { | ||
| const { loading, error, data } = useQuery(PROFILE_QUERY); | ||
|
|
||
| if (loading) { | ||
| return <p>loading..</p>; | ||
| } | ||
|
|
||
| if (error) { | ||
| return JSON.stringify(error); | ||
| } | ||
|
|
||
| return ( | ||
| <> | ||
| <p>user name: {data.profile.displayname}</p> | ||
| <p>name: {data.profile.name}</p> | ||
| </> | ||
| ); | ||
| }; | ||
|
|
||
| export default withApollo(ProfilePage); | ||
|
|
||
| ``` | ||
|
|
||
| Eso es todo. Ahora la página de Perfil se renderizará en el servidor. No necesitas hacer nada en `getInitialProps`. Todas las consultas se resuelven en el servidor. | ||
|
|
||
| Si no deseas realizar SSR de la página anterior, puedes pasar `{ssr: false}` al hoc. | ||
|
|
||
| ``` | ||
| export default withApollo(ProfilePage, { ssr: false }); | ||
| ``` | ||
|
Comment on lines
+98
to
+100
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win Specify the code fence language. Change the fence at Line 98 to 🧰 Tools🪛 markdownlint-cli2 (0.23.1)[warning] 98-98: Fenced code blocks should have a language specified (MD040, fenced-code-language) 🤖 Prompt for AI AgentsSource: Linters/SAST tools |
||
|
|
||
| Si lo deseas, también puedes acceder a la instancia de `apolloClient` en `getInitialProps`. | ||
|
|
||
| ```js | ||
| ProfilePage.getInitialProps = ctx => { | ||
| const apolloClient = ctx.apolloClient; | ||
| }; | ||
| ``` | ||
|
|
||
| ## SSR con autenticación | ||
|
|
||
| A menudo, el servidor de graphQL requiere un `AuthorizationToken` para autorizar las solicitudes. Podemos usar los encabezados recibidos en el servidor para extraer el token de las cookies del lado del cliente. | ||
|
|
||
| ```js | ||
| // hocs/withApollo.js | ||
| import withApollo from 'nextjs-with-apollo'; | ||
| import fetch from 'isomorphic-unfetch'; | ||
| import { InMemoryCache } from 'apollo-cache-inmemory'; | ||
| import ApolloClient from 'apollo-client'; | ||
| import { HttpLink } from 'apollo-link-http'; | ||
| import { ApolloLink } from 'apollo-link'; | ||
| import { setContext } from 'apollo-link-context'; | ||
| import cookie from 'cookie'; | ||
| import get from 'lodash/get'; | ||
|
|
||
| const isServer = typeof window === 'undefined'; | ||
|
|
||
| const getToken = headers => { | ||
| const COOKIE_NAME = 'your_auth_cookie_name' | ||
| const cookies = isServer ? get(headers, 'cookie', '') : document.cookie; | ||
|
|
||
| return get(cookie.parse(cookies), COOKIE_NAME, ''); | ||
| }; | ||
|
|
||
| const attachAuth = headers => () => { | ||
| const token = getToken(headers); | ||
|
|
||
| return { | ||
| headers: { | ||
| authorization: `Bearer ${token}` | ||
| } | ||
| }; | ||
| }; | ||
|
|
||
| const createApolloClient = ({ initialState, headers = {} }) => { | ||
| const authLink = () => setContext(attachAuth(headers)); | ||
|
|
||
| const httpLink = new HttpLink({ | ||
| credentials: 'include', | ||
| uri: GRAPHQL_ENDPOINT, | ||
| fetch | ||
|
Comment on lines
+145
to
+151
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win Define the authenticated GraphQL endpoint. The example references 🤖 Prompt for AI Agents |
||
| }); | ||
|
|
||
| return new ApolloClient({ | ||
| ssrMode: isServer, | ||
| link: ApolloLink.from([authLink(), httpLink]), | ||
| cache: new InMemoryCache().restore(initialState || {}) | ||
| }); | ||
| }; | ||
|
|
||
| export default withApollo(createApolloClient); | ||
| ``` | ||
|
|
||
| ## Licencia | ||
| Siéntete libre de usar el código, está publicado bajo la licencia MIT. | ||
|
|
||
| [npm-image]:https://img.shields.io/npm/v/nextjs-with-apollo.svg | ||
| [npm-url]:https://www.npmjs.com/package/nextjs-with-apollo | ||
| [license-image]:https://img.shields.io/github/license/adikari/nextjs-with-apollo.svg | ||
| [license-url]:https://github.com/adikari/nextjs-with-apollo/blob/master/LICENSE | ||
|
|
||
| [lgtm-image]:https://img.shields.io/lgtm/grade/javascript/g/adikari/nextjs-with-apollo.svg?logo=lgtm&logoWidth=18 | ||
| [lgtm-url]:https://lgtm.com/projects/g/adikari/nextjs-with-apollo/context:javascript | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Make the basic query example executable.
The snippet uses
gqlwithout importing it. It declaresQUERYbut passesPROFILE_QUERYtouseQuery. A reader copying this example will get undefined identifiers. Add the project’sgqlimport and useQUERY, or rename the declaration.🤖 Prompt for AI Agents