Skip to content
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

docs: Update the middleware / endpoint documentation #4442

Merged
merged 1 commit into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/docs/codesandbox.sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function findCodeSandboxes(
for (let lineNo = 0; lineNo < lines.length; lineNo++) {
const line = lines[lineNo];
newLines.push(line);
const match = line.match(/(.*)<(CodeSandbox|CodeFile) src=["']([^"']*)["'][^/]*>$/);
const match = line.match(/(.*)<(CodeSandbox|CodeFile) src=["']([^"']*)["'].*>$/);
if (match) {
const [, prefix, tag, srcPath] = match;
const content: string[] = [];
Expand Down
1 change: 1 addition & 0 deletions packages/docs/public/docs/qwikcity/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The images in this folder were created: https://docs.google.com/presentation/d/1HjlWpOpnPAmjdxEV7F2uttjvkWf1FOLvXaWMcxGLs38/
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 3 additions & 5 deletions packages/docs/src/routes/demo/demo-reset.css
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,17 @@ demo a:active {
}

demo ul {
margin-top: 1em;
margin-bottom: 1em;
margin-top: 0.5em;
margin-bottom: 0.5em;
margin-left: 0;
margin-right: 0;
padding-left: 40px;
list-style-type: square;
}

demo li {
margin-top: 0.5em;
margin-bottom: 0.5em;
padding-left: 0;
list-style-type: none;
list-style-type: disc;
margin-left: 1em;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { $, component$ } from '@builder.io/qwik';
import { Image, useImageProvider } from 'qwik-image';
import type { ImageTransformerProps } from 'qwik-image';
import {
Image,
type ImageTransformerProps,
useImageProvider,
} from 'qwik-image';

export default component$(() => {
const imageTransformer$ = $(
({ src, width, height }: ImageTransformerProps): string => {
// Here you can set your favourite image loader CDN
// Here you can set your favorite image loaders service
return `https://cdn.builder.io/api/v1/${src}?height=${height}&width=${width}}&format=webp&fit=fill`;
}
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ basePathname, json }) => {
json(200, { basePathname });
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({
cacheControl,
headers,
json,
}) => {
cacheControl({ maxAge: 42, public: true });
const obj: Record<string, string> = {};
headers.forEach((value, key) => (obj[key] = value));
json(200, obj);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { component$ } from '@builder.io/qwik';
import { type RequestHandler } from '@builder.io/qwik-city';

export const onRequest: RequestHandler = async ({ redirect }) => {
if (!isLoggedIn()) {
throw redirect(308, '/login');
}
};

export default component$(() => {
return <div>You are logged in.</div>;
});

function isLoggedIn() {
return true; // Mock login as true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ cookie, json }) => {
let count = cookie.get('Qwik.demo.count')?.number() || 0;
count++;
cookie.set('Qwik.demo.count', count);
json(200, { count });
};
10 changes: 10 additions & 0 deletions packages/docs/src/routes/demo/qwikcity/middleware/env/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ env, json }) => {
json(200, {
USER: env.get('USER'),
MODE_ENV: env.get('MODE_ENV'),
PATH: env.get('PATH'),
SHELL: env.get('SHELL'),
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ error }) => {
throw error(500, 'ERROR: Demonstration of an error response.');
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ exit }) => {
throw exit();
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async (requestEvent) => {
const writableStream = requestEvent.getWritableStream();
const writer = writableStream.getWriter();
const encoder = new TextEncoder();

writer.write(encoder.encode('Hello World'));
await wait(100);
writer.write(encoder.encode('After 100ms'));
await wait(100);
writer.write(encoder.encode('After 200ms'));
await wait(100);
writer.write(encoder.encode('END'));
writer.close();
};

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ headersSent, json }) => {
if (!headersSent) {
json(200, { response: 'default response' });
}
};

export const onRequest: RequestHandler = async ({ status }) => {
status(200);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ headers, json }) => {
headers.set('X-SRF-TOKEN', Math.random().toString(36).replace('0.', ''));
const obj: Record<string, string> = {};
headers.forEach((value, key) => (obj[key] = value));
json(200, obj);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ html }) => {
html(
200,
`
<html>
<body>
<h1>HTML response</h1>
</body>
</html>`
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ json }) => {
json(200, { hello: 'world' });
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onRequest: RequestHandler = async ({ locale, request }) => {
const acceptLanguage = request.headers.get('accept-language');
const [languages] = acceptLanguage?.split(';') || ['?', '?'];
const [preferredLanguage] = languages.split(',');
locale(preferredLanguage);
};

export const onGet: RequestHandler = async ({ locale, json }) => {
json(200, { locale: locale() });
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onRequest: RequestHandler = async ({ method, json }) => {
json(200, { method });
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { type RequestHandler } from '@builder.io/qwik-city';

// Generic function `onRequest` is executed first
export const onRequest: RequestHandler = async ({ next, sharedMap, json }) => {
const log: string[] = [];
sharedMap.set('log', log);

log.push('onRequest start');
await next(); // Execute next middleware function (onGet)
log.push('onRequest end');

json(200, log);
};

// Specific functions such as `onGet` are executed next
export const onGet: RequestHandler = async ({ next, sharedMap }) => {
const log = sharedMap.get('log') as string[];

log.push('onGET start');
// execute next middleware function
// (in our case, there are no more middleware functions nor components.)
await next();
log.push('onGET end');
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ params, json }) => {
json(200, { params });
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ html }) => {
html(
200,
`
<form id="myForm" method="POST">
<input type="text" name="project" value="Qwik"/>
<input type="text" name="url" value="http://qwik.builder.io"/>
</form>
<script>myForm.submit()</script>`
);
};

export const onPost: RequestHandler = async ({ parseBody, json }) => {
json(200, { body: await parseBody() });
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ platform, json }) => {
json(200, Object.keys(platform));
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ send, url }) => {
const response = await fetch(
new URL('/demo/qwikcity/middleware/json/', url)
);
send(response);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ query, json }) => {
const obj: Record<string, string> = {};
query.forEach((v, k) => (obj[k] = v));
json(200, obj);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ redirect, url }) => {
throw redirect(
308,
new URL('/demo/qwikcity/middleware/status/', url).toString()
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ json, request }) => {
const obj: Record<string, string> = {};
request.headers.forEach((v, k) => (obj[k] = v));
json(200, { headers: obj });
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async (requestEvent) => {
const response = new Response('Hello World', {
status: 200,
headers: {
'Content-Type': 'text/plain',
},
});
requestEvent.send(response);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { component$ } from '@builder.io/qwik';
import {
routeLoader$,
type RequestHandler,
type Cookie,
} from '@builder.io/qwik-city';

interface User {
username: string;
email: string;
}

export const onRequest: RequestHandler = async ({
sharedMap,
cookie,
send,
}) => {
const user = loadUserFromCookie(cookie);
if (user) {
sharedMap.set('user', user);
} else {
throw send(401, 'NOT_AUTHORIZED');
}
};

function loadUserFromCookie(cookie: Cookie): User | null {
// this is where you would check cookie for user.
if (cookie) {
// just return mock user for this demo.
return {
username: `Mock User`,
email: `mock@users.com`,
};
} else {
return null;
}
}

export const useUser = routeLoader$(({ sharedMap }) => {
return sharedMap.get('user') as User;
});

export default component$(() => {
const log = useUser();
return (
<div>
{log.value.username} ({log.value.email})
</div>
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ status, getWritableStream }) => {
status(200);
const stream = getWritableStream();
const writer = stream.getWriter();
writer.write(new TextEncoder().encode('Hello World!'));
writer.close();
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ text }) => {
text(200, 'Text based response.');
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onRequest: RequestHandler = async ({ next, sharedMap, json }) => {
const log: string[] = [];
sharedMap.set('log', log);

log.push('onRequest');
if (isLoggedIn()) {
// normal behavior call next middleware
await next();
} else {
// If not logged in throw to prevent implicit call to the next middleware.
throw json(404, log);
}
};

export const onGet: RequestHandler = async ({ sharedMap }) => {
const log = sharedMap.get('log') as string[];
log.push('onGET');
};

function isLoggedIn() {
return false; // always return false as mock example
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { type RequestHandler } from '@builder.io/qwik-city';

export const onGet: RequestHandler = async ({ url, json }) => {
json(200, { url: url.toString() });
};