[ci] format

This commit is contained in:
matthewp 2022-03-16 16:17:34 +00:00 committed by GitHub Actions
parent 4c25a1c2ea
commit 279774c48e
17 changed files with 84 additions and 101 deletions

View file

@ -5,13 +5,13 @@ export default defineConfig({
vite: {
server: {
cors: {
credentials: true
credentials: true,
},
proxy: {
'/api': {
target: 'http://127.0.0.1:8085',
changeOrigin: true,
}
},
},
},
},

View file

@ -41,36 +41,36 @@ const routes = [
match: /\/api\/cart/,
async handle(req, res) {
res.writeHead(200, {
'Content-Type': 'application/json'
'Content-Type': 'application/json',
});
let cookie = req.headers.cookie;
let userId = cookie ? lightcookie.parse(cookie)['user-id'] : '1'; // default for testing
if(!userId || !userCartItems.has(userId)) {
if (!userId || !userCartItems.has(userId)) {
res.end(JSON.stringify({ items: [] }));
return;
}
let items = userCartItems.get(userId);
let array = Array.from(items.values());
res.end(JSON.stringify({ items: array }));
}
},
},
{
match: /\/api\/add-to-cart/,
async handle(req, res) {
let body = '';
req.on('data', chunk => body += chunk);
return new Promise(resolve => {
req.on('data', (chunk) => (body += chunk));
return new Promise((resolve) => {
req.on('end', () => {
let cookie = req.headers.cookie;
let userId = lightcookie.parse(cookie)['user-id'];
let msg = JSON.parse(body);
if(!userCartItems.has(userId)) {
if (!userCartItems.has(userId)) {
userCartItems.set(userId, new Map());
}
let cart = userCartItems.get(userId);
if(cart.has(msg.id)) {
if (cart.has(msg.id)) {
cart.get(msg.id).count++;
} else {
cart.set(msg.id, { id: msg.id, name: msg.name, count: 1 });
@ -82,8 +82,8 @@ const routes = [
res.end(JSON.stringify({ ok: true }));
});
});
}
}
},
},
];
export async function apiHandler(req, res) {

View file

@ -22,7 +22,7 @@ const origin = MODE === 'development' ? `http://127.0.0.1:3000` : `http://127.0.
async function get<T>(endpoint: string, cb: (response: Response) => Promise<T>): Promise<T> {
const response = await fetch(`${origin}${endpoint}`, {
credentials: 'same-origin'
credentials: 'same-origin',
});
if (!response.ok) {
// TODO make this better...
@ -46,14 +46,14 @@ export async function getProduct(id: number): Promise<Product> {
}
export async function getUser(): Promise<User> {
return get<User>(`/api/user`, async response => {
return get<User>(`/api/user`, async (response) => {
const user: User = await response.json();
return user;
});
}
export async function getCart(): Promise<Cart> {
return get<Cart>(`/api/cart`, async response => {
return get<Cart>(`/api/cart`, async (response) => {
const cart: Cart = await response.json();
return cart;
});
@ -66,11 +66,11 @@ export async function addToUserCart(id: number | string, name: string): Promise<
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
'Cache': 'no-cache'
Cache: 'no-cache',
},
body: JSON.stringify({
id,
name
})
name,
}),
});
}

View file

@ -1,6 +1,5 @@
import lightcookie from 'lightcookie';
export function isLoggedIn(request: Request): boolean {
const cookie = request.headers.get('cookie');
const parsed = lightcookie.parse(cookie);

View file

@ -1,10 +1,9 @@
export function post(params, request) {
return new Response(null, {
status: 301,
headers: {
'Location': '/',
'Set-Cookie': 'user-id=1; Path=/; Max-Age=2592000'
}
Location: '/',
'Set-Cookie': 'user-id=1; Path=/; Max-Age=2592000',
},
});
}

View file

@ -37,7 +37,7 @@ export class App {
if (!routeData) {
return new Response(null, {
status: 404,
statusText: 'Not found'
statusText: 'Not found',
});
}
}
@ -75,13 +75,13 @@ export class App {
headers: request.headers,
});
if(result.type === 'response') {
if (result.type === 'response') {
return result.response;
}
let html = result.html;
return new Response(html, {
status: 200
status: 200,
});
}
async #loadRenderers(): Promise<Renderer[]> {

View file

@ -11,7 +11,7 @@ function createRequestFromNodeRequest(req: IncomingMessage): Request {
const entries = Object.entries(req.headers as Record<string, any>);
let request = new Request(url, {
method: req.method || 'GET',
headers: new Headers(entries)
headers: new Headers(entries),
});
return request;
}

View file

@ -402,23 +402,22 @@ async function generatePath(pathname: string, opts: StaticBuildOptions, gopts: G
route: pageData.route,
routeCache,
site: astroConfig.buildOptions.site,
ssr: opts.astroConfig.buildOptions.experimentalSsr
}
ssr: opts.astroConfig.buildOptions.experimentalSsr,
};
let body: string;
if(pageData.route.type === 'endpoint') {
if (pageData.route.type === 'endpoint') {
const result = await callEndpoint(mod as unknown as EndpointHandler, options);
if(result.type === 'response') {
throw new Error(`Returning a Response from an endpoint is not supported in SSG mode.`)
if (result.type === 'response') {
throw new Error(`Returning a Response from an endpoint is not supported in SSG mode.`);
}
body = result.body;
} else {
const result = await render(options);
// If there's a redirect or something, just do nothing.
if(result.type !== 'html') {
if (result.type !== 'html') {
return;
}
body = result.html;

View file

@ -7,15 +7,13 @@ import { call as callEndpoint } from '../index.js';
import { getParamsAndProps, GetParamsAndPropsError } from '../../render/core.js';
import { createRequest } from '../../render/request.js';
export async function call(ssrOpts: SSROptions) {
try {
const [, mod] = await preload(ssrOpts);
return await callEndpoint(mod as unknown as EndpointHandler, {
...ssrOpts,
ssr: ssrOpts.astroConfig.buildOptions.experimentalSsr
ssr: ssrOpts.astroConfig.buildOptions.experimentalSsr,
});
} catch (e: unknown) {
await errorHandler(e, { viteServer: ssrOpts.viteServer, filePath: ssrOpts.filePath });
throw e;

View file

@ -4,48 +4,38 @@ import { renderEndpoint } from '../../runtime/server/index.js';
import { getParamsAndProps, GetParamsAndPropsError } from '../render/core.js';
import { createRequest } from '../render/request.js';
export type EndpointOptions = Pick<RenderOptions,
'logging' |
'headers' |
'method' |
'origin' |
'route' |
'routeCache' |
'pathname' |
'route' |
'site' |
'ssr'
>;
export type EndpointOptions = Pick<RenderOptions, 'logging' | 'headers' | 'method' | 'origin' | 'route' | 'routeCache' | 'pathname' | 'route' | 'site' | 'ssr'>;
type EndpointCallResult = {
type: 'simple',
body: string
} | {
type: 'response',
response: Response
};
type EndpointCallResult =
| {
type: 'simple';
body: string;
}
| {
type: 'response';
response: Response;
};
export async function call(mod: EndpointHandler, opts: EndpointOptions): Promise<EndpointCallResult> {
const paramsAndPropsResp = await getParamsAndProps({ ...opts, mod: (mod as any) });
const paramsAndPropsResp = await getParamsAndProps({ ...opts, mod: mod as any });
if (paramsAndPropsResp === GetParamsAndPropsError.NoMatchingStaticPath) {
throw new Error(`[getStaticPath] route pattern matched, but no matching static path found. (${opts.pathname})`);
}
const [params] = paramsAndPropsResp;
const request = createRequest(opts.method, opts.pathname, opts.headers, opts.origin,
opts.site, opts.ssr);
const request = createRequest(opts.method, opts.pathname, opts.headers, opts.origin, opts.site, opts.ssr);
const response = await renderEndpoint(mod, request, params);
if(response instanceof Response) {
if (response instanceof Response) {
return {
type: 'response',
response
response,
};
}
return {
type: 'simple',
body: response.body
body: response.body,
};
}

View file

@ -74,7 +74,7 @@ export interface RenderOptions {
headers: Headers;
}
export async function render(opts: RenderOptions): Promise<{ type: 'html', html: string } | { type: 'response', response: Response }> {
export async function render(opts: RenderOptions): Promise<{ type: 'html'; html: string } | { type: 'response'; response: Response }> {
const { headers, legacyBuild, links, logging, origin, markdownRender, method, mod, pathname, scripts, renderers, resolve, route, routeCache, site, ssr } = opts;
const paramsAndPropsRes = await getParamsAndProps({
@ -109,12 +109,12 @@ export async function render(opts: RenderOptions): Promise<{ type: 'html', html:
scripts,
ssr,
method,
headers
headers,
});
let page = await renderPage(result, Component, pageProps, null);
if(page.type === 'response') {
if (page.type === 'response') {
return page;
}
@ -130,9 +130,9 @@ export async function render(opts: RenderOptions): Promise<{ type: 'html', html:
if (!legacyBuild && !/<!doctype html/i.test(html)) {
html = '<!DOCTYPE html>\n' + html;
}
return {
type: 'html',
html
html,
};
}

View file

@ -41,9 +41,7 @@ export interface SSROptions {
export type ComponentPreload = [Renderer[], ComponentInstance];
export type RenderResponse =
{ type: 'html', html: string } |
{ type: 'response', response: Response };
export type RenderResponse = { type: 'html'; html: string } | { type: 'response'; response: Response };
const svelteStylesRE = /svelte\?svelte&type=style/;
@ -186,7 +184,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO
return {
type: 'html',
html
html,
};
}

View file

@ -18,10 +18,9 @@ export interface AstroRequest {
method: string;
}
export type AstroRequestSSR = AstroRequest
export type AstroRequestSSR = AstroRequest;
export function createRequest(method: string, pathname: string, headers: Headers,
origin: string, site: Site, ssr: boolean): AstroRequest {
export function createRequest(method: string, pathname: string, headers: Headers, origin: string, site: Site, ssr: boolean): AstroRequest {
const url = new URL('.' + pathname, new URL(origin));
const canonicalURL = utilCanonicalURL('.' + pathname, site ?? url.origin);
@ -31,10 +30,10 @@ export function createRequest(method: string, pathname: string, headers: Headers
canonicalURL,
params: {},
headers,
method
method,
};
if(!ssr) {
if (!ssr) {
// Headers are only readable if using SSR-mode. If not, make it an empty headers
// object, so you can't do something bad.
request.headers = new Headers();
@ -42,7 +41,7 @@ export function createRequest(method: string, pathname: string, headers: Headers
// Disallow using query params.
request.url = new URL(request.url);
for(const [key] of request.url.searchParams) {
for (const [key] of request.url.searchParams) {
request.url.searchParams.delete(key);
}
}

View file

@ -9,9 +9,9 @@ import { renderSlot } from '../../runtime/server/index.js';
import { warn, LogOptions } from '../logger.js';
function onlyAvailableInSSR(name: string) {
return function() {
return function () {
// TODO add more guidance when we have docs and adapters.
throw new Error(`Oops, you are trying to use ${name}, which is only available with SSR.`)
throw new Error(`Oops, you are trying to use ${name}, which is only available with SSR.`);
};
}
@ -94,14 +94,16 @@ export function createResult(args: CreateResultArgs): SSRResult {
__proto__: astroGlobal,
props,
request,
redirect: args.ssr ? (path: string) => {
return new Response(null, {
status: 301,
headers: {
Location: path
}
});
} : onlyAvailableInSSR('Astro.redirect'),
redirect: args.ssr
? (path: string) => {
return new Response(null, {
status: 301,
headers: {
Location: path,
},
});
}
: onlyAvailableInSSR('Astro.redirect'),
resolve(path: string) {
if (!legacyBuild) {
let extra = `This can be replaced with a dynamic import like so: await import("${path}")`;

View file

@ -434,10 +434,9 @@ async function replaceHeadInjection(result: SSRResult, html: string): Promise<st
}
// Calls a component and renders it into a string of HTML
export async function renderToString(result: SSRResult, componentFactory: AstroComponentFactory,
props: any, children: any): Promise<string> {
export async function renderToString(result: SSRResult, componentFactory: AstroComponentFactory, props: any, children: any): Promise<string> {
const Component = await componentFactory(result, props, children);
if(!isAstroComponent(Component)) {
if (!isAstroComponent(Component)) {
throw new Error('Cannot return a Response from a nested component.');
}
@ -450,20 +449,20 @@ export async function renderPage(
componentFactory: AstroComponentFactory,
props: any,
children: any
): Promise<{ type: 'html', html: string } | { type: 'response', response: Response }> {
): Promise<{ type: 'html'; html: string } | { type: 'response'; response: Response }> {
const response = await componentFactory(result, props, children);
if(isAstroComponent(response)) {
if (isAstroComponent(response)) {
let template = await renderAstroComponent(response);
const html = await replaceHeadInjection(result, template);
return {
type: 'html',
html
html,
};
} else {
return {
type: 'response',
response
response,
};
}
}

View file

@ -43,12 +43,12 @@ function writeHtmlResponse(res: http.ServerResponse, statusCode: number, html: s
async function writeWebResponse(res: http.ServerResponse, webResponse: Response) {
const { status, headers, body } = webResponse;
res.writeHead(status, Object.fromEntries(headers.entries()));
if(body) {
if (body) {
const reader = body.getReader();
while(true) {
while (true) {
const { done, value } = await reader.read();
if(done) break;
if(value) {
if (done) break;
if (value) {
res.write(value);
}
}
@ -57,7 +57,7 @@ async function writeWebResponse(res: http.ServerResponse, webResponse: Response)
}
async function writeSSRResult(result: RenderResponse, res: http.ServerResponse, statusCode: 200 | 404) {
if(result.type === 'response') {
if (result.type === 'response') {
const { response } = result;
await writeWebResponse(res, response);
return;
@ -194,9 +194,9 @@ async function handleRequest(
};
// Route successfully matched! Render it.
if(route.type === 'endpoint') {
if (route.type === 'endpoint') {
const result = await callEndpoint(options);
if(result.type === 'response') {
if (result.type === 'response') {
await writeWebResponse(res, result.response);
} else {
res.writeHead(200);

View file

@ -97,7 +97,7 @@ export function rollupPluginAstroBuildHTML(options: PluginOptions): VitePlugin {
viteServer,
});
if(response.type !== 'html') {
if (response.type !== 'html') {
continue;
}