Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 173 additions & 0 deletions README.es-ES.md
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]
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/7588b3bdb457430687e3688bf2cd6121)](https://www.codacy.com/manual/subash.adhikari/nextjs-with-apollo)
[![Dependencies](https://img.shields.io/david/adikari/nextjs-with-apollo?logo=dependabot)](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);
Comment on lines +56 to +72

Copy link
Copy Markdown

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 gql without importing it. It declares QUERY but passes PROFILE_QUERY to useQuery. A reader copying this example will get undefined identifiers. Add the project’s gql import and use QUERY, or rename the declaration.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.es-ES.md` around lines 56 - 72, Update the ProfilePage example so its
identifiers are defined and consistent: import the project’s gql helper
alongside the existing imports, and pass the declared QUERY constant to useQuery
instead of the undefined 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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 ```js to satisfy Markdown linting and preserve syntax highlighting.

🧰 Tools
🪛 markdownlint-cli2 (0.23.1)

[warning] 98-98: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.es-ES.md` around lines 98 - 100, Update the Markdown code fence
surrounding the withApollo(ProfilePage, { ssr: false }) example in
README.es-ES.md to specify the JavaScript language using a js fence, while
preserving the example content.

Source: 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

Copy link
Copy Markdown

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

Define the authenticated GraphQL endpoint.

The example references GRAPHQL_ENDPOINT at Line 150, but does not declare it. The earlier example declares a different constant, GRAPHQL_URL. Define GRAPHQL_ENDPOINT in this example or use the existing endpoint constant.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.es-ES.md` around lines 145 - 151, Update the createApolloClient
example to resolve the undefined GRAPHQL_ENDPOINT reference by reusing the
existing GRAPHQL_URL constant or declaring GRAPHQL_ENDPOINT before the HttpLink
configuration.

});

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