Skip to content

Commit

Permalink
fix(router): add support for server-side data fetching with catch-all…
Browse files Browse the repository at this point in the history
… routes (#602)
  • Loading branch information
brandonroberts authored Aug 14, 2023
1 parent cfda180 commit dd8922f
Show file tree
Hide file tree
Showing 12 changed files with 82 additions and 8 deletions.
13 changes: 11 additions & 2 deletions apps/analog-app-e2e-cypress/src/e2e/app.cy.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import * as app from '../support/app.po';

describe('My Store', () => {
beforeEach(() => cy.visit('/'));

it(`Given the user has navigated to the home page
Then the app title is visible`, () => {
cy.visit('/');
app.getTitle().contains(/my store/i);
});

it(`Given the user has navigated an invalid page then the page not found title is visible`, () => {
cy.visit('/bad');
app.get404Title().contains(/page not found/i);
});

it(`Given the user has navigated an invalid nested page then the page not found title is visible`, () => {
cy.visit('/shipping/bad');
app.getNested404Title().contains(/shipping page not found/i);
});
});
5 changes: 5 additions & 0 deletions apps/analog-app-e2e-cypress/src/support/app.po.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export const getTitle = () => cy.contains('h1', /my store/i);

export const get404Title = () => cy.contains('h2', /page not found/i);

export const getNested404Title = () =>
cy.contains('h2', /shipping page not found/i);
3 changes: 2 additions & 1 deletion apps/analog-app/src/app/cart.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Product } from './products';
})
export class CartService {
items: Product[] = [];
private readonly apiURL = import.meta.env.VITE_ANALOG_PUBLIC_BASE_URL;

constructor(private http: HttpClient) {}

Expand All @@ -25,7 +26,7 @@ export class CartService {

getShippingPrices() {
return this.http.get<{ type: string; price: number }[]>(
'/assets/shipping.json'
`${this.apiURL}/assets/shipping.json`
);
}
}
8 changes: 8 additions & 0 deletions apps/analog-app/src/app/pages/[...slug].page.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Component } from '@angular/core';

@Component({
selector: 'app-page-not-found',
standalone: true,
template: ` <h2>Page Not Found</h2> `,
})
export default class PageNotFoundComponent {}
9 changes: 9 additions & 0 deletions apps/analog-app/src/app/pages/[...slug].server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { PageServerLoad } from '@analogjs/router';

export function load({ params }: PageServerLoad) {
console.log('params', params);

return {
loaded: true,
};
}
8 changes: 8 additions & 0 deletions apps/analog-app/src/app/pages/shipping/[...slug].page.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Component } from '@angular/core';

@Component({
selector: 'app-shipping-page-not-found',
standalone: true,
template: ` <h2>Shipping Page Not Found</h2> `,
})
export default class ShippingPageNotFoundComponent {}
9 changes: 9 additions & 0 deletions apps/analog-app/src/app/pages/shipping/[...slug].server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { PageServerLoad } from '@analogjs/router';

export function load({ params }: PageServerLoad) {
console.log('slug', params?.['slug']);

return {
loaded: true,
};
}
15 changes: 14 additions & 1 deletion apps/analog-app/src/public/assets/shipping.json
Original file line number Diff line number Diff line change
@@ -1 +1,14 @@
[]
[
{
"type": "Overnight",
"price": 25.99
},
{
"type": "2-Day",
"price": 9.99
},
{
"type": "Postal",
"price": 2.99
}
]
8 changes: 8 additions & 0 deletions apps/analog-app/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
/// <reference types="vite/client" />

interface ImportMetaEnv {
readonly VITE_ANALOG_PUBLIC_BASE_URL: string;
}

interface ImportMeta {
readonly env: ImportMetaEnv;
}
5 changes: 4 additions & 1 deletion packages/router/src/lib/route-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ export function toRouteConfig(routeMeta: RouteMeta | undefined): RouteConfig {
};

if (PAGE_ENDPOINTS[routeConfig[ANALOG_META_KEY].endpointKey]) {
const { queryParams, fragment: hash, params } = route;
const { queryParams, fragment: hash, params, parent } = route;
const segment =
parent?.url.map((segment) => segment.path).join('/') || '';
const url = new URL('', import.meta.env['VITE_ANALOG_PUBLIC_BASE_URL']);
url.pathname = `/api/_analog${routeConfig[ANALOG_META_KEY].endpoint}`;
url.search = `${new URLSearchParams(queryParams).toString()}`;
Expand All @@ -44,6 +46,7 @@ export function toRouteConfig(routeMeta: RouteMeta | undefined): RouteConfig {
Object.keys(params).forEach((param) => {
url.pathname = url.pathname.replace(`[${param}]`, params[param]);
});
url.pathname = url.pathname.replace('**', segment);

if ((globalThis as any).$fetch) {
return (globalThis as any).$fetch(url.pathname);
Expand Down
1 change: 1 addition & 0 deletions packages/router/src/lib/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ function toRoutes(rawRoutes: RawRoute[], files: Files): Route[] {
// get endpoint path
const rawEndpoint = rawRoute.filename
.replace(/\.page\.ts$/, '')
.replace(/\[\.{3}.+\]/, '**') // [...not-found] => **
.split(APP_DIR)[1];

// replace periods, remove (index) paths
Expand Down
6 changes: 3 additions & 3 deletions packages/vite-plugin-nitro/src/lib/utils/get-page-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ export function getPageHandlers({ workspaceRoot, rootDir }: GetHandlersArgs) {
const route = endpointFile
.replace(path.resolve(workspaceRoot, rootDir, 'src/app'), '')
.replace(/\.server\.ts$/, '')
.replace(/\[\.{3}]/g, '**')
.replace(/\[\.{3}(\w+)]/g, '**:$1')
.replace(/\[\.{3}(.+)\]/g, '**:$1')
.replace(/\[\.{3}(\w+)\]/g, '**:$1')
.replace(/\/\((.*?)\)$/, '/-$1-')
.replace(/\[(\w+)]/g, ':$1')
.replace(/\[(\w+)\]/g, ':$1')
.replace(/\./g, '/');

return {
Expand Down

0 comments on commit dd8922f

Please sign in to comment.