Unverified Commit c48340cd authored by Luis Fernando Alvarez D's avatar Luis Fernando Alvarez D Committed by GitHub

Move next/router to Typescript (#7019)

Added types to next/router
parent 8b136a6f
/* global window */ /* global window */
import React from 'react' 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 { RouterContext } from 'next-server/dist/lib/router-context'
import { RequestContext } from 'next-server/dist/lib/request-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 router: null, // holds the actual router instance
readyCallbacks: [], readyCallbacks: [],
ready (cb) { ready(cb: () => void) {
if (this.router) return cb() if (this.router) return cb()
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
this.readyCallbacks.push(cb) this.readyCallbacks.push(cb)
} }
} },
} }
// const x = SingletonRouter as IRealRouter
// Create public properties and methods of the router in the SingletonRouter // Create public properties and methods of the router in the SingletonRouter
const urlPropertyFields = ['pathname', 'route', 'query', 'asPath'] const urlPropertyFields = ['pathname', 'route', 'query', 'asPath']
const propertyFields = ['components'] const propertyFields = ['components']
...@@ -23,9 +41,9 @@ const coreMethodFields = ['push', 'replace', 'reload', 'back', 'prefetch', 'befo ...@@ -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 // Events is a static property on the router, the router doesn't have to be initialized to use it
Object.defineProperty(SingletonRouter, 'events', { Object.defineProperty(SingletonRouter, 'events', {
get () { get() {
return _Router.events return Router.events
} },
}) })
propertyFields.concat(urlPropertyFields).forEach((field) => { propertyFields.concat(urlPropertyFields).forEach((field) => {
...@@ -34,29 +52,33 @@ 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 // The value might get changed as we change routes and this is the
// proper way to access it // proper way to access it
Object.defineProperty(SingletonRouter, field, { Object.defineProperty(SingletonRouter, field, {
get () { get() {
throwIfNoRouter() const router = getRouter() as any
return SingletonRouter.router[field] return router[field] as string
} },
}) })
}) })
coreMethodFields.forEach((field) => { coreMethodFields.forEach((field) => {
SingletonRouter[field] = (...args) => { // We don't really know the types here, so we add them later instead
throwIfNoRouter() (SingletonRouter as any)[field] = (...args: any[]) => {
return SingletonRouter.router[field](...args) const router = getRouter() as any
return router[field](...args)
} }
}) })
routerEvents.forEach((event) => { routerEvents.forEach((event) => {
SingletonRouter.ready(() => { SingletonRouter.ready(() => {
_Router.events.on(event, (...args) => { Router.events.on(event, (...args) => {
const eventField = `on${event.charAt(0).toUpperCase()}${event.substring(1)}` const eventField = `on${event.charAt(0).toUpperCase()}${event.substring(1)}`
if (SingletonRouter[eventField]) { const singletonRouter = SingletonRouter as any
if (singletonRouter[eventField]) {
try { try {
SingletonRouter[eventField](...args) singletonRouter[eventField](...args)
} catch (err) { } catch (err) {
// tslint:disable-next-line:no-console
console.error(`Error when running the Router event: ${eventField}`) console.error(`Error when running the Router event: ${eventField}`)
// tslint:disable-next-line:no-console
console.error(`${err.message}\n${err.stack}`) console.error(`${err.message}\n${err.stack}`)
} }
} }
...@@ -64,25 +86,29 @@ routerEvents.forEach((event) => { ...@@ -64,25 +86,29 @@ routerEvents.forEach((event) => {
}) })
}) })
function throwIfNoRouter () { function getRouter() {
if (!SingletonRouter.router) { if (!SingletonRouter.router) {
const message = 'No router instance found.\n' + const message = 'No router instance found.\n' +
'You should only use "next/router" inside the client side of your app.\n' 'You should only use "next/router" inside the client side of your app.\n'
throw new Error(message) throw new Error(message)
} }
return SingletonRouter.router
} }
// Export the SingletonRouter and this is the public API. // Export the SingletonRouter and this is the public API.
export default SingletonRouter export default SingletonRouter as ISingletonRouter
// Reexport the withRoute HOC // Reexport the withRoute HOC
export { default as withRouter } from './with-router' 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) return React.useContext(RouterContext)
} }
export function useRequest () { export function useRequest() {
return React.useContext(RequestContext) return React.useContext(RequestContext)
} }
...@@ -93,32 +119,30 @@ export function useRequest () { ...@@ -93,32 +119,30 @@ export function useRequest () {
// Create a router and assign it as the singleton instance. // Create a router and assign it as the singleton instance.
// This is used in client side when we are initilizing the app. // This is used in client side when we are initilizing the app.
// This should **not** use inside the server. // This should **not** use inside the server.
export const createRouter = function (...args) { export const createRouter = (...args: RouterArgs) => {
SingletonRouter.router = new _Router(...args) SingletonRouter.router = new Router(...args)
SingletonRouter.readyCallbacks.forEach(cb => cb()) SingletonRouter.readyCallbacks.forEach((cb) => cb())
SingletonRouter.readyCallbacks = [] SingletonRouter.readyCallbacks = []
return SingletonRouter.router 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 // This function is used to create the `withRouter` router instance
export function makePublicRouterInstance (router) { export function makePublicRouterInstance(router: Router): IPublicRouterInstance {
const instance = {} const _router = router as any
const instance = {} as any
for (const property of urlPropertyFields) { for (const property of urlPropertyFields) {
if (typeof router[property] === 'object') { if (typeof _router[property] === 'object') {
instance[property] = { ...router[property] } // makes sure query is not stateful instance[property] = { ..._router[property] } // makes sure query is not stateful
continue 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 // 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) => { propertyFields.forEach((field) => {
// Here we need to use Object.defineProperty because, we need to return // Here we need to use Object.defineProperty because, we need to return
...@@ -126,15 +150,15 @@ export function makePublicRouterInstance (router) { ...@@ -126,15 +150,15 @@ export function makePublicRouterInstance (router) {
// The value might get changed as we change routes and this is the // The value might get changed as we change routes and this is the
// proper way to access it // proper way to access it
Object.defineProperty(instance, field, { Object.defineProperty(instance, field, {
get () { get() {
return router[field] return _router[field]
} },
}) })
}) })
coreMethodFields.forEach((field) => { coreMethodFields.forEach((field) => {
instance[field] = (...args) => { instance[field] = (...args: any[]) => {
return router[field](...args) return _router[field](...args)
} }
}) })
......
...@@ -4,6 +4,11 @@ declare module 'next-server/constants'; ...@@ -4,6 +4,11 @@ declare module 'next-server/constants';
declare module 'webpack/lib/GraphHelpers'; declare module 'webpack/lib/GraphHelpers';
declare module 'unfetch' 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' { declare module 'next-server/dist/lib/data-manager-context' {
import * as all from 'next-server/lib/data-manager-context' import * as all from 'next-server/lib/data-manager-context'
export = all export = all
...@@ -14,6 +19,20 @@ declare module 'next-server/dist/lib/router-context' { ...@@ -14,6 +19,20 @@ declare module 'next-server/dist/lib/router-context' {
export = all 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' { declare module 'next/dist/compiled/nanoid/index.js' {
function nanoid(size?: number): string; function nanoid(size?: number): string;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment