Skip to content

Commit

Permalink
chore: format
Browse files Browse the repository at this point in the history
formatted cca6628
  • Loading branch information
Remix Run Bot committed Jan 8, 2022
1 parent cca6628 commit 81dd8f0
Show file tree
Hide file tree
Showing 12 changed files with 79 additions and 82 deletions.
2 changes: 1 addition & 1 deletion docs/tutorials/blog.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ We're going to make a new route to render at the "/posts" URL. Before we do that
<Link to="/posts">Posts</Link>
```

You can put it anywhere you like, you might want to just delete everything that's there.
You can put it anywhere you like, you might want to just delete everything that's there.

💿 Either way you will also need to import `Link`:

Expand Down
2 changes: 1 addition & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ Most examples should:

To create an example, simply copy/paste the [`template`](template) directory into a new one with a sensible name, make the changes you need for your example, update the `README.md` and open a PR!

Thanks!
Thanks!
5 changes: 1 addition & 4 deletions examples/client-side-validation/app/root.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import type {
ActionFunction,
LinksFunction,
LoaderFunction} from "remix";
import type { ActionFunction, LinksFunction, LoaderFunction } from "remix";
import {
json,
Links,
Expand Down
3 changes: 2 additions & 1 deletion examples/multiple-forms/app/routes/invitations.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Form, json, useLoaderData, redirect } from "remix";
import type { LoaderFunction, ActionFunction } from "remix";
import { Invitation, sendInvitation } from "~/data.server";
import type { Invitation} from "~/data.server";
import { sendInvitation } from "~/data.server";
import {
getInvitations,
resendInvitation,
Expand Down
15 changes: 7 additions & 8 deletions examples/redis-upstash-session/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,25 @@ In this example we use Redis (Upstash) to store the session info.
## Preview

Sorry no preview as you'll need an account on Upstash for it

## Example

### Prerequisites
### Prerequisites

- Create a free account at https://upstash.com/
- Create a new Redis database
- Duplicate the local `.env.example` file to `.env` and change the URL & Token environment variables
with your database info.
with your database info.
- Run `$ npm install`
- Run `$ npm run dev`

## Usage
## Usage

- The first time you run the project you a new session will be created for you and saved on `Upstash`
- If you refresh before the session expires (10 secs) the page you'll see the session's info.
- After the has expired you'll get back to square one and create a new session.
For more info check the following files:

For more info check the following files:

- [app/routes/index.tsx](app/routes/index.tsx)
- [app/sessions.server.ts](app/sessions.server.ts)
Expand All @@ -34,6 +36,3 @@ with your database info.
## Related Links

- https://upstash.com/



33 changes: 17 additions & 16 deletions examples/redis-upstash-session/app/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@

import { json, LoaderFunction, useLoaderData } from "remix"
import type { LoaderFunction} from "remix";
import { json, useLoaderData } from "remix";
import { commitSession, getSession } from "~/sessions.server";

export const loader: LoaderFunction = async ({request}) => {
export const loader: LoaderFunction = async ({ request }) => {
// Get the session from the cookie
const session = await getSession(request.headers.get("Cookie"));
const myStoredData = session.get('myStoredData');
const myStoredData = session.get("myStoredData");
// If no session found (was never created or was expired) create a new session.
if (!myStoredData) {
session.set('myStoredData', 'Some data');
session.set("myStoredData", "Some data");
return json(
{
message: "Created new session",
message: "Created new session"
},
{
headers: {
"Set-Cookie": await commitSession(session),
},
} )
"Set-Cookie": await commitSession(session)
}
}
);
}
// If session was found, present the session info.
return json({
message: `Showing Session info: ${myStoredData}`
})
}
message: `Showing Session info: ${myStoredData}`
});
};

export default function() {
const data = useLoaderData()
return <div>{data.message}</div>
}
export default function () {
const data = useLoaderData();
return <div>{data.message}</div>;
}
19 changes: 7 additions & 12 deletions examples/redis-upstash-session/app/sessions.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import {
createCookie,
} from "remix";
import { createCookie } from "remix";
import { createUpstashSessionStorage } from "~/sessions/upstash.server";

// This will set the length of the session.
Expand All @@ -11,15 +9,12 @@ const expires = new Date();
expires.setSeconds(expires.getSeconds() + EXPIRATION_DURATION_IN_SECONDS);

const sessionCookie = createCookie("__session", {
secrets: ["r3m1xr0ck1"],
sameSite: true,
expires
secrets: ["r3m1xr0ck1"],
sameSite: true,
expires
});

const { getSession, commitSession, destroySession } =
createUpstashSessionStorage({ cookie: sessionCookie });

const { getSession, commitSession, destroySession } = createUpstashSessionStorage(
{ cookie: sessionCookie }
);


export { getSession, commitSession, destroySession };
export { getSession, commitSession, destroySession };
66 changes: 35 additions & 31 deletions examples/redis-upstash-session/app/sessions/upstash.server.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,21 @@
import * as crypto from "crypto";

import {
createSessionStorage,
} from "remix";
import { createSessionStorage } from "remix";


const upstashRedisRestUrl = process.env.UPSTASH_REDIS_REST_URL
const upstashRedisRestUrl = process.env.UPSTASH_REDIS_REST_URL;

const headers = {
Authorization: `Bearer ${process.env.UPSTASH_REDIS_REST_TOKEN}`,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
Accept: "application/json",
"Content-Type": "application/json"
};

const expiresToSeconds = (expires) => {
const now = new Date()
const expiresToSeconds = expires => {
const now = new Date();
const expiresDate = new Date(expires);
const secondsDelta = expiresDate.getSeconds() - now.getSeconds();
return secondsDelta < 0 ? 0 : secondsDelta;
}

};

// For more info check https://remix.run/docs/en/v1/api/remix#createsessionstorage
export function createUpstashSessionStorage({ cookie }: any) {
Expand All @@ -28,40 +24,48 @@ export function createUpstashSessionStorage({ cookie }: any) {
async createData(data, expires) {
while (true) {
// Create a random id - taken from the core `createFileSessionStorage` Remix function.
let randomBytes = crypto.randomBytes(8);
let id = Buffer.from(randomBytes).toString("hex");
const randomBytes = crypto.randomBytes(8);
const id = Buffer.from(randomBytes).toString("hex");
// Call Upstash Redis HTTP API. Set expiration according to the cookie `expired property.
// Note the use of the `expiresToSeconds` that converts date to seconds.
await fetch(`${upstashRedisRestUrl}/set/${id}?EX=${expiresToSeconds(expires)}`, {
method: 'post', body: JSON.stringify({ data }),
headers
})
// Note the use of the `expiresToSeconds` that converts date to seconds.
await fetch(
`${upstashRedisRestUrl}/set/${id}?EX=${expiresToSeconds(expires)}`,
{
method: "post",
body: JSON.stringify({ data }),
headers
}
);
return id;
}
},
async readData(id) {
console.log(id)
console.log(id);
const response = await fetch(`${upstashRedisRestUrl}/get/${id}`, {
headers
})
});
try {
const { result } = await response.json()
return (JSON.parse(result)).data;
const { result } = await response.json();
return JSON.parse(result).data;
} catch (error) {
return null
return null;
}
},
async updateData(id, data, expires) {
await fetch(`${upstashRedisRestUrl}/set/${id}?EX=${expiresToSeconds(expires)}`, {
method: 'post', body: JSON.stringify({ data }),
headers
})
await fetch(
`${upstashRedisRestUrl}/set/${id}?EX=${expiresToSeconds(expires)}`,
{
method: "post",
body: JSON.stringify({ data }),
headers
}
);
},
async deleteData(id) {
await fetch(`${upstashRedisRestUrl}/del/${id}`, {
method: 'post',
method: "post",
headers
})
});
}
})
});
}
2 changes: 1 addition & 1 deletion examples/tailwindcss/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ Relevant files:

## Related Links

[Tailwind CSS](https://tailwindcss.com)
[Tailwind CSS](https://tailwindcss.com)
4 changes: 2 additions & 2 deletions examples/tailwindcss/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import {
ScrollRestoration
} from "remix";

import tailwind from './tailwind.css'
import tailwind from "./tailwind.css";

export function links() {
return [{ rel: "stylesheet", href: tailwind}]
return [{ rel: "stylesheet", href: tailwind }];
}

export default function App() {
Expand Down
4 changes: 2 additions & 2 deletions examples/tailwindcss/app/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export default function Index() {
return <h1 className="text-6xl text-red-700 font-bold">Hello World!</h1>;
}
return <h1 className="text-6xl text-red-700 font-bold">Hello World!</h1>;
}
6 changes: 3 additions & 3 deletions examples/tailwindcss/tailwind.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module.exports = {
content: ["./app/**/*.{ts,tsx,js,jsx}"],
theme: {
extend: {},
extend: {}
},
plugins: [],
}
plugins: []
};

0 comments on commit 81dd8f0

Please sign in to comment.