parent
8b136a6f9d
commit
c48340cd8c
2 changed files with 81 additions and 38 deletions
|
@ -1,20 +1,38 @@
|
|||
/* global window */
|
||||
import React from 'react'
|
||||
import _Router from 'next-server/dist/lib/router/router'
|
||||
import Router, { IRouterInterface } from 'next-server/dist/lib/router/router'
|
||||
import { RouterContext } from 'next-server/dist/lib/router-context'
|
||||
import { RequestContext } from 'next-server/dist/lib/request-context'
|
||||
|
||||
const SingletonRouter = {
|
||||
type ClassArguments<T> = T extends new(...args: infer U) => any ? U : any
|
||||
|
||||
type RouterArgs = ClassArguments<typeof Router>
|
||||
|
||||
interface ISingletonRouterBase {
|
||||
router: Router | null
|
||||
readyCallbacks: Array<() => any>
|
||||
ready(cb: () => any): void
|
||||
}
|
||||
|
||||
export interface IPublicRouterInstance extends IRouterInterface, Pick<Router, | 'components' | 'push' | 'replace' | 'reload' | 'back' | 'prefetch' | 'beforePopState'> {
|
||||
events: typeof Router['events']
|
||||
}
|
||||
|
||||
export interface ISingletonRouter extends ISingletonRouterBase, IPublicRouterInstance {}
|
||||
|
||||
const SingletonRouter: ISingletonRouterBase = {
|
||||
router: null, // holds the actual router instance
|
||||
readyCallbacks: [],
|
||||
ready (cb) {
|
||||
ready(cb: () => void) {
|
||||
if (this.router) return cb()
|
||||
if (typeof window !== 'undefined') {
|
||||
this.readyCallbacks.push(cb)
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
// const x = SingletonRouter as IRealRouter
|
||||
|
||||
// Create public properties and methods of the router in the SingletonRouter
|
||||
const urlPropertyFields = ['pathname', 'route', 'query', 'asPath']
|
||||
const propertyFields = ['components']
|
||||
|
@ -23,9 +41,9 @@ const coreMethodFields = ['push', 'replace', 'reload', 'back', 'prefetch', 'befo
|
|||
|
||||
// Events is a static property on the router, the router doesn't have to be initialized to use it
|
||||
Object.defineProperty(SingletonRouter, 'events', {
|
||||
get () {
|
||||
return _Router.events
|
||||
}
|
||||
get() {
|
||||
return Router.events
|
||||
},
|
||||
})
|
||||
|
||||
propertyFields.concat(urlPropertyFields).forEach((field) => {
|
||||
|
@ -34,29 +52,33 @@ propertyFields.concat(urlPropertyFields).forEach((field) => {
|
|||
// The value might get changed as we change routes and this is the
|
||||
// proper way to access it
|
||||
Object.defineProperty(SingletonRouter, field, {
|
||||
get () {
|
||||
throwIfNoRouter()
|
||||
return SingletonRouter.router[field]
|
||||
}
|
||||
get() {
|
||||
const router = getRouter() as any
|
||||
return router[field] as string
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
coreMethodFields.forEach((field) => {
|
||||
SingletonRouter[field] = (...args) => {
|
||||
throwIfNoRouter()
|
||||
return SingletonRouter.router[field](...args)
|
||||
// We don't really know the types here, so we add them later instead
|
||||
(SingletonRouter as any)[field] = (...args: any[]) => {
|
||||
const router = getRouter() as any
|
||||
return router[field](...args)
|
||||
}
|
||||
})
|
||||
|
||||
routerEvents.forEach((event) => {
|
||||
SingletonRouter.ready(() => {
|
||||
_Router.events.on(event, (...args) => {
|
||||
Router.events.on(event, (...args) => {
|
||||
const eventField = `on${event.charAt(0).toUpperCase()}${event.substring(1)}`
|
||||
if (SingletonRouter[eventField]) {
|
||||
const singletonRouter = SingletonRouter as any
|
||||
if (singletonRouter[eventField]) {
|
||||
try {
|
||||
SingletonRouter[eventField](...args)
|
||||
singletonRouter[eventField](...args)
|
||||
} catch (err) {
|
||||
// tslint:disable-next-line:no-console
|
||||
console.error(`Error when running the Router event: ${eventField}`)
|
||||
// tslint:disable-next-line:no-console
|
||||
console.error(`${err.message}\n${err.stack}`)
|
||||
}
|
||||
}
|
||||
|
@ -64,25 +86,29 @@ routerEvents.forEach((event) => {
|
|||
})
|
||||
})
|
||||
|
||||
function throwIfNoRouter () {
|
||||
function getRouter() {
|
||||
if (!SingletonRouter.router) {
|
||||
const message = 'No router instance found.\n' +
|
||||
'You should only use "next/router" inside the client side of your app.\n'
|
||||
throw new Error(message)
|
||||
}
|
||||
return SingletonRouter.router
|
||||
}
|
||||
|
||||
// Export the SingletonRouter and this is the public API.
|
||||
export default SingletonRouter
|
||||
export default SingletonRouter as ISingletonRouter
|
||||
|
||||
// Reexport the withRoute HOC
|
||||
export { default as withRouter } from './with-router'
|
||||
|
||||
export function useRouter () {
|
||||
// Export the actual Router class, which is usually used inside the server
|
||||
export { Router }
|
||||
|
||||
export function useRouter() {
|
||||
return React.useContext(RouterContext)
|
||||
}
|
||||
|
||||
export function useRequest () {
|
||||
export function useRequest() {
|
||||
return React.useContext(RequestContext)
|
||||
}
|
||||
|
||||
|
@ -93,32 +119,30 @@ export function useRequest () {
|
|||
// Create a router and assign it as the singleton instance.
|
||||
// This is used in client side when we are initilizing the app.
|
||||
// This should **not** use inside the server.
|
||||
export const createRouter = function (...args) {
|
||||
SingletonRouter.router = new _Router(...args)
|
||||
SingletonRouter.readyCallbacks.forEach(cb => cb())
|
||||
export const createRouter = (...args: RouterArgs) => {
|
||||
SingletonRouter.router = new Router(...args)
|
||||
SingletonRouter.readyCallbacks.forEach((cb) => cb())
|
||||
SingletonRouter.readyCallbacks = []
|
||||
|
||||
return SingletonRouter.router
|
||||
}
|
||||
|
||||
// Export the actual Router class, which is usually used inside the server
|
||||
export const Router = _Router
|
||||
|
||||
// This function is used to create the `withRouter` router instance
|
||||
export function makePublicRouterInstance (router) {
|
||||
const instance = {}
|
||||
export function makePublicRouterInstance(router: Router): IPublicRouterInstance {
|
||||
const _router = router as any
|
||||
const instance = {} as any
|
||||
|
||||
for (const property of urlPropertyFields) {
|
||||
if (typeof router[property] === 'object') {
|
||||
instance[property] = { ...router[property] } // makes sure query is not stateful
|
||||
if (typeof _router[property] === 'object') {
|
||||
instance[property] = { ..._router[property] } // makes sure query is not stateful
|
||||
continue
|
||||
}
|
||||
|
||||
instance[property] = router[property]
|
||||
instance[property] = _router[property]
|
||||
}
|
||||
|
||||
// Events is a static property on the router, the router doesn't have to be initialized to use it
|
||||
instance.events = _Router.events
|
||||
instance.events = Router.events
|
||||
|
||||
propertyFields.forEach((field) => {
|
||||
// Here we need to use Object.defineProperty because, we need to return
|
||||
|
@ -126,15 +150,15 @@ export function makePublicRouterInstance (router) {
|
|||
// The value might get changed as we change routes and this is the
|
||||
// proper way to access it
|
||||
Object.defineProperty(instance, field, {
|
||||
get () {
|
||||
return router[field]
|
||||
}
|
||||
get() {
|
||||
return _router[field]
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
coreMethodFields.forEach((field) => {
|
||||
instance[field] = (...args) => {
|
||||
return router[field](...args)
|
||||
instance[field] = (...args: any[]) => {
|
||||
return _router[field](...args)
|
||||
}
|
||||
})
|
||||
|
19
packages/next/types/index.d.ts
vendored
19
packages/next/types/index.d.ts
vendored
|
@ -4,6 +4,11 @@ declare module 'next-server/constants';
|
|||
declare module 'webpack/lib/GraphHelpers';
|
||||
declare module 'unfetch'
|
||||
|
||||
declare module 'next/router' {
|
||||
import * as all from 'next/client/router'
|
||||
export = all
|
||||
}
|
||||
|
||||
declare module 'next-server/dist/lib/data-manager-context' {
|
||||
import * as all from 'next-server/lib/data-manager-context'
|
||||
export = all
|
||||
|
@ -14,6 +19,20 @@ declare module 'next-server/dist/lib/router-context' {
|
|||
export = all
|
||||
}
|
||||
|
||||
declare module 'next-server/dist/lib/router/router' {
|
||||
import * as all from 'next-server/lib/router/router'
|
||||
export = all
|
||||
}
|
||||
|
||||
declare module 'next-server/dist/lib/request-context' {
|
||||
import * as all from 'next-server/lib/request-context'
|
||||
export = all
|
||||
}
|
||||
|
||||
declare module 'next-server/dist/lib/utils' {
|
||||
export function loadGetInitialProps(Component: any, ctx: any): Promise<any>
|
||||
export function execOnce(fn: any): (...args: any[]) => void
|
||||
}
|
||||
|
||||
declare module 'next/dist/compiled/nanoid/index.js' {
|
||||
function nanoid(size?: number): string;
|
||||
|
|
Loading…
Reference in a new issue