Skip to content

Commit 164ac2c

Browse files
committed
NEW: translation EN (current sessions.md file) to ES (new sessions.es.md file)
1 parent 96ba90d commit 164ac2c

File tree

2 files changed

+38
-38
lines changed

2 files changed

+38
-38
lines changed

docs/advanced/sessions.es.md

Lines changed: 38 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,101 +1,102 @@
1-
# Sessions
1+
# Sesiones
22

3-
Sessions allow you to persist a user's data between multiple requests. Sessions work by creating and returning a unique cookie alongside the HTTP response when a new session is initialized. Browsers will automatically detect this cookie and include it in future requests. This allows Vapor to automatically restore a specific user's session in your request handler.
3+
Las sesiones te permiten conservar los datos de un usuario entre varias solicitudes. Las sesiones funcionan creando y devolviendo una cookie única junto con la respuesta HTTP cuando se inicializa una nueva sesión. Los navegadores detectarán automáticamente esta cookie y la incluirán en futuras solicitudes. Esto permite que Vapor restaure automáticamente la sesión de un usuario específico en su controlador de solicitudes.
44

5-
Sessions are great for front-end web applications built in Vapor that serve HTML directly to web browsers. For APIs, we recommend using stateless, [token-based authentication](../security/authentication.md) to persist user data between requests.
5+
Las sesiones son ideales para aplicaciones web front-end creadas en Vapor que sirven HTML directamente a los navegadores web. Para APIs, recomendamos usar autenticación sin estado, [autenticación basada en tokens](../security/authentication.md) para persistir los datos del usuario entre solicitudes.
66

7-
## Configuration
7+
## Configuración
88

9-
10-
To use sessions in a route, the request must pass through `SessionsMiddleware`. The easiest way to achieve this is by adding this middleware globally. It is recommended that you do add this after you declare the cookie factory. This is because Sessions is a struct, therefore it is a value type, and not a reference type. Since it is a value type, you must set the value before using `SessionsMiddleware`.
9+
Para usar sesiones en una ruta, la solicitud debe pasar por `SessionsMiddleware`. La forma más fácil de lograr esto es agregando este middleware globalmente. Se recomienda que lo agregues después de declarar la fábrica de cookies. Esto se debe a que Sessions es una estructura, por lo tanto, es un tipo por valor y no un tipo por referencia. Dado que es un tipo por valor, debes establecer el valor antes de usar `SessionsMiddleware`.
1110

1211
```swift
1312
app.middleware.use(app.sessions.middleware)
1413
```
1514

16-
If only a subset of your routes utilize sessions, you can instead add `SessionsMiddleware` to a route group.
15+
Si solo un subconjunto de tus rutas utiliza sesiones, puedes añadir `SessionsMiddleware` a un grupo de rutas.
1716

1817
```swift
1918
let sessions = app.grouped(app.sessions.middleware)
2019
```
2120

22-
The HTTP cookie generated by sessions can be configured using `app.sessions.configuration`. You can change the cookie name and declare a custom function for generating cookie values.
21+
La cookie HTTP generada por las sesiones se puede configurar usando `app.sessions.configuration`. Puedes cambiar el nombre de la cookie y declarar una función personalizada para generar valores de las cookies.
2322

2423
```swift
25-
// Change the cookie name to "foo".
24+
// Cambia el nombre de la cookie a "foo".
2625
app.sessions.configuration.cookieName = "foo"
2726

28-
// Configures cookie value creation.
27+
// Configura la creación del valor de la cookie.
2928
app.sessions.configuration.cookieFactory = { sessionID in
3029
.init(string: sessionID.string, isSecure: true)
3130
}
3231

3332
app.middleware.use(app.sessions.middleware)
3433
```
3534

36-
By default, Vapor will use `vapor_session` as the cookie name.
37-
38-
## Drivers
35+
De manera predeterminada, Vapor usará `vapor_session` como nombre de la cookie.
3936

40-
Session drivers are responsible for storing and retrieving session data by identifier. You can create custom drivers by conforming to the `SessionDriver` protocol.
37+
## Controladores
4138

42-
!!! warning
43-
The session driver should be configured _before_ adding `app.sessions.middleware` to your application.
39+
Los controladores de sesión son responsables de almacenar y recuperar datos de sesión por identificador. Puedes crear controladores personalizados conformando al protocolo `SessionDriver`.
4440

45-
### In-Memory
41+
!!! warning "Advertencia"
42+
El controlador de sesión debe configurarse _antes_ de añadir `app.sessions.middleware` a tu aplicación.
43+
44+
### En Memoria
4645

47-
Vapor utilizes in-memory sessions by default. In-memory sessions require zero configuration and do not persist between application launches which makes them great for testing. To enable in-memory sessions manually, use `.memory`:
46+
Vapor utiliza sesiones en memoria por defecto. Las sesiones en memoria no requieren ninguna configuración y no persisten entre lanzamientos de la aplicación, lo que las hace ideales para realizar pruebas. Para habilitar en memoria las sesiones de forma manual, usa `.memory`:
4847

4948
```swift
5049
app.sessions.use(.memory)
5150
```
5251

53-
For production use cases, take a look at the other session drivers which utilize databases to persist and share sessions across multiple instances of your app.
52+
Para casos de uso en producción, echa un vistazo a los otros controladores de sesión que utilizan bases de datos para persistir y compartir sesiones a través de múltiples instancias de tu aplicación.
5453

5554
### Fluent
5655

57-
Fluent includes support for storing session data in your application's database. This section assumes you have [configured Fluent](../fluent/overview.md) and can connect to a database. The first step is to enable the Fluent sessions driver.
56+
Fluent incluye soporte para almacenar datos de sesión en la base de datos de tu aplicación. Esta sección supone que has [configurado Fluent](../fluent/overview.md) y puedes conectarte a una base de datos. El primer paso es habilitar el controlador de sesiones de Fluent.
5857

5958
```swift
6059
import Fluent
6160

6261
app.sessions.use(.fluent)
6362
```
6463

65-
This will configure sessions to use the application's default database. To specify a specific database, pass the database's identifier.
64+
Esto configurará las sesiones para usar la base de datos por defecto de la aplicación. Para especificar una base de datos específica, pasa el identificador de la base de datos.
6665

6766
```swift
6867
app.sessions.use(.fluent(.sqlite))
6968
```
7069

7170
Finally, add `SessionRecord`'s migration to your database's migrations. This will prepare your database for storing session data in the `_fluent_sessions` schema.
7271

72+
Por último, añade la migración de `SessionRecord` a las migraciones de tu base de datos. Esto preparará tu base de datos para almacenar datos de sesión en el esquema `_fluent_sessions`.
73+
7374
```swift
7475
app.migrations.add(SessionRecord.migration)
7576
```
7677

77-
Make sure to run your application's migrations after adding the new migration. Sessions will now be stored in your application's database allowing them to persist between restarts and be shared between multiple instances of your app.
78+
Asegúrate de ejecutar las migraciones de tu aplicación después de añadir la nueva migración. Las sesiones ahora se almacenarán en la base de datos de tu aplicación, permitiendo que se persistan entre reinicios y sean compartidas entre varias instancias de tu aplicación.
7879

7980
### Redis
8081

81-
Redis provides support for storing session data in your configured Redis instance. This section assumes you have [configured Redis](../redis/overview.md) and can send commands to the Redis instance.
82+
Redis proporciona soporte para almacenar datos de sesión en tu instancia Redis configurada. Esta sección supone que has [configurado Redis](../redis/overview.md) y puedes enviar comandos a la instancia Redis.
8283

83-
To use Redis for Sessions, select it when configuring your application:
84+
Para usar Redis para sesiones, selecciónalo al configurar tu aplicación:
8485

8586
```swift
8687
import Redis
8788

8889
app.sessions.use(.redis)
8990
```
9091

91-
This will configure sessions to use the Redis sessions driver with the default behavior.
92-
93-
!!! seealso
94-
Refer to [Redis → Sessions](../redis/sessions.md) for more detailed information about Redis and Sessions.
92+
Esto configurará las sesiones para usar el controlador de sesiones Redis con el comportamiento por defecto.
9593

96-
## Session Data
94+
!!! seealso "Ver también"
95+
Consulte [Redis → Sessions](../redis/sessions.md) para obtener información más detallada sobre Redis y Sessions.
96+
97+
## Datos de Sesión
9798

98-
Now that sessions are configured, you are ready to persist data between requests. New sessions are initialized automatically when data is added to `req.session`. The example route handler below accepts a dynamic route parameter and adds the value to `req.session.data`.
99+
Ahora que las sesiones están configuradas, estás listo para persistir datos entre solicitudes. Las nuevas sesiones se inicializan automáticamente cuando se añaden datos a `req.session`. A continuación, el controlador de ruta de ejemplo acepta un parámetro de ruta dinámica y agrega el valor a `req.session.data`.
99100

100101
```swift
101102
app.get("set", ":value") { req -> HTTPStatus in
@@ -104,41 +105,41 @@ app.get("set", ":value") { req -> HTTPStatus in
104105
}
105106
```
106107

107-
Use the following request to initialize a session with the name Vapor.
108+
Utiliza la siguiente solicitud para inicializar una sesión con el nombre Vapor.
108109

109110
```http
110111
GET /set/vapor HTTP/1.1
111112
content-length: 0
112113
```
113114

114-
You should receive a response similar to the following:
115+
Deberías recibir una respuesta similar a la siguiente:
115116

116117
```http
117118
HTTP/1.1 200 OK
118119
content-length: 0
119120
set-cookie: vapor-session=123; Expires=Fri, 10 Apr 2020 21:08:09 GMT; Path=/
120121
```
121122

122-
Notice the `set-cookie` header has been added automatically to the response after adding data to `req.session`. Including this cookie in subsequent requests will allow access to the session data.
123+
Observa que la cabecera `set-cookie` se ha añadido automáticamente a la respuesta después de añadir datos a `req.session`. Incluir esta cookie en solicitudes posteriores permitirá acceder a los datos de la sesión.
123124

124-
Add the following route handler for accessing the name value from the session.
125+
Añade el siguiente controlador de ruta para acceder al valor del nombre desde la sesión.
125126

126127
```swift
127128
app.get("get") { req -> String in
128129
req.session.data["name"] ?? "n/a"
129130
}
130131
```
131132

132-
Use the following request to access this route while making sure to pass the cookie value from the previous response.
133+
Utiliza la siguiente solicitud para acceder a esta ruta asegurándote de pasar el valor de la cookie de la respuesta anterior.
133134

134135
```http
135136
GET /get HTTP/1.1
136137
cookie: vapor-session=123
137138
```
138139

139-
You should see the name Vapor returned in the response. You can add or remove data from the session as you see fit. Session data will be synchronized with the session driver automatically before returning the HTTP response.
140+
Deberías ver el nombre Vapor devuelto en la respuesta. Puedes añadir o eliminar datos de la sesión como creas conveniente. Los datos de la sesión se sincronizarán con el controlador de sesión automáticamente antes de devolver la respuesta HTTP.
140141

141-
To end a session, use `req.session.destroy`. This will delete the data from the session driver and invalidate the session cookie.
142+
Para finalizar una sesión, utiliza `req.session.destroy`. Esto eliminará los datos del controlador de sesión e invalidará la cookie de sesión.
142143

143144
```swift
144145
app.get("del") { req -> HTTPStatus in

docs/advanced/sessions.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ Sessions are great for front-end web applications built in Vapor that serve HTML
66

77
## Configuration
88

9-
109
To use sessions in a route, the request must pass through `SessionsMiddleware`. The easiest way to achieve this is by adding this middleware globally. It is recommended that you do add this after you declare the cookie factory. This is because Sessions is a struct, therefore it is a value type, and not a reference type. Since it is a value type, you must set the value before using `SessionsMiddleware`.
1110

1211
```swift

0 commit comments

Comments
 (0)