adiconado tipagem rota de fornt
This commit is contained in:
parent
e1985dd867
commit
a5ca1748af
9 changed files with 175 additions and 2 deletions
|
|
@ -7,3 +7,4 @@ export * from "./uuid"
|
|||
export * from "./provedores"
|
||||
export * from "./ecosistema"
|
||||
export * from "./variaveisComuns"
|
||||
export * from "./tipagemRotas"
|
||||
|
|
|
|||
68
src/tipagemRotas.ts
Normal file
68
src/tipagemRotas.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
/** Gerar uma classe que facilita a gestão de rotas com a tipagem das querys */
|
||||
|
||||
export class TipagemRotas<T = { [q: string]: string }> {
|
||||
/** Prefixo da url */
|
||||
PREFIXO: string | undefined = undefined
|
||||
|
||||
_caminhoParcial: string
|
||||
/** Ao criar novo obijeto de tipagem de rota é necessário passar o caminho parcial
|
||||
** export const mCaminho = new TipagemRotas<{q:string}>("/caminho")
|
||||
*/
|
||||
constructor(caminhoParcial: string, PREFIXO: string | undefined) {
|
||||
this._caminhoParcial = caminhoParcial
|
||||
if (PREFIXO) this.PREFIXO = PREFIXO
|
||||
}
|
||||
|
||||
/** Retorna o caminho completo da rota
|
||||
** console.log(mCaminho.caminho)
|
||||
** "/caminho"
|
||||
*/
|
||||
get caminho() {
|
||||
return this.PREFIXO + this._caminhoParcial
|
||||
}
|
||||
/** Define o caminho completo da rota
|
||||
** mCaminho.caminho = "/novoCaminho"
|
||||
** console.log(mCaminho.caminho)
|
||||
** "/novoCaminho"
|
||||
** */
|
||||
set caminho(caminhoParcial: string) {
|
||||
this._caminhoParcial = caminhoParcial
|
||||
}
|
||||
|
||||
/** Retorna o caminho completo da rota com a query
|
||||
** console.log(mCaminho.resolve({q:"query"}))
|
||||
** "http://localhost:3000/caminho?q=query"
|
||||
*/
|
||||
|
||||
resolve(query: T) {
|
||||
const url = new URL(window.location.href)
|
||||
url.pathname = this.PREFIXO + this._caminhoParcial
|
||||
const queryKeys =
|
||||
typeof query == "object" && query ? Object.entries(query) : [[query, ""]]
|
||||
|
||||
for (const [key, value] of queryKeys) {
|
||||
url.searchParams.set(String(key), value)
|
||||
}
|
||||
return url.href
|
||||
}
|
||||
|
||||
/** Vai para a url
|
||||
** mCaminho.ir({q:"query"})
|
||||
** window.location.href = "http://localhost:3000/caminho?q=query"
|
||||
*/
|
||||
ir(query: T) {
|
||||
window.location.href = this.resolve(query)
|
||||
}
|
||||
|
||||
/** Retorna os parametros da url
|
||||
** console.log(mCaminho.parametros())
|
||||
** {q:"query"}
|
||||
*/
|
||||
|
||||
parametros() {
|
||||
const url = new URL(window.location.href)
|
||||
const query = url.searchParams
|
||||
const queryObj = Object.fromEntries(query.entries())
|
||||
return queryObj as T
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue