Last active
October 29, 2021 07:10
-
-
Save Lxxyx/912091078ae7089d1eaec6cf80d739ea to your computer and use it in GitHub Desktop.
Pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default defineConfig({ | |
routes: [{ | |
baseDir: 'api', | |
}] | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
useContext | |
} from '@midwayjs/hooks' | |
import { | |
Get, | |
Post, | |
Delete, | |
Query, | |
Param, | |
Header, | |
Validate, | |
Pipe, | |
} from '@midwayjs/hooks-pipe' | |
import { Authorized, useCurrentUser } from '@midwayjs/auth' | |
/** | |
* 问题 | |
* 1. Pipe 自定义路由与文件系统路由的冲突 | |
*/ | |
export default Pipe( | |
Get('/'), | |
Authorized(), | |
async () => { | |
const user = useCurrentUser() | |
return user.name | |
} | |
) | |
type BookQueryParam = { | |
page: string | |
count: string | |
} | |
// HTTP POST [page, string] | |
export const get = async (page: String, count: string) => { | |
} | |
// HTTP GET /?page=1&count=10 | |
export const get = Pipe( | |
Get('/'), | |
Query<BookQueryParam>(), | |
async () => { | |
const ctx = useContext() | |
ctx.query // BookQueryParam | |
return findBooks(ctx.query.page, ctx.query.count) | |
} | |
) | |
type Request = { | |
query?: any | |
data?: any | |
header?: any | |
param?: any | |
} | |
export const Pipe( | |
Get(), | |
async () => { | |
} | |
) | |
// frontend | |
get({ query: { page: '1', count: '10' } }) | |
class DTO { | |
@String() | |
name: string | |
} | |
type CreateBookParam = { | |
id: string | |
} | |
export const mtop = Pipe( | |
Mtop(), | |
async () => { | |
} | |
) | |
export const timer = Pipe( | |
Timer({ | |
type: 'crontab', | |
trigger: '* * * * * *' | |
}), | |
Middleware([logger]), | |
Validator([Time]), | |
async () => { | |
} | |
) | |
export const post = Pipe( | |
Post('/:id'), | |
Param<CreateBookParam>(), | |
Validate([DTO]), | |
async (dto: DTO) => { | |
const ctx = useContext() | |
ctx.param // CreateBookParam | |
if (dto.name !== ctx.user.name) { | |
ctx.status = 403 | |
return | |
} | |
return createBook(ctx.param.id, dto.name) | |
} | |
) | |
// frontend | |
post({ name: '柴可夫斯基' }, { param: { id: '' } }) | |
type HeaderParam = { | |
token: string | |
} | |
export const del = Pipe( | |
Delete('/'), | |
Authorized(), | |
Header<HeaderParam>(), | |
async () => { | |
const ctx = useContext() | |
ctx.headers // HeaderParam | |
return deleteBook(ctx.header.token) | |
} | |
) | |
// frontend | |
del({ header: { token: '123' } }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment