Last active: a year ago
Common package json scripts
{
"scripts": {
"pretty": "prettier --write \"./**/*.{js,jsx,ts,tsx,json,md,mdx,css}\" --ignore-unknown",
"pretty-check": "prettier \"./**/*.{js,jsx,ts,tsx,json,md,mdx,css}\" --ignore-unknown --check",
"prepare": "husky install"
}
}
Last active: a year ago
Common prettier configuration
node_modules
out
.next
public
dist
build
Last active: a year ago
Common prettier configuration
{
"semi": true,
"singleQuote": true,
"endOfLine": "lf"
}
Last active: a year ago
Common editorconfig
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
Last active: a year ago
Common editorconfig
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
Last active: a year ago
Axum fallback and hello world route
use axum::{
http::{StatusCode, Uri},
response::IntoResponse,
};
use tracing::info;
pub mod baidu;
pub async fn hello() -> &'static str {
"Hello World!"
}
/// Fallback route handler for handling unmatched routes.
///
/// This asynchronous function takes a `Uri` as an argument, representing the unmatched route.
/// It logs a message indicating that the specified route is not found and returns a standard
/// "Not Found" response with a `StatusCode` of `404`.
///
/// # Arguments
///
Last active: a year ago
Axum custom add version for each response middleware
use crate::error::AppResult;
use anyhow::anyhow;
use axum::{
body::Body, extract::Request, http::HeaderValue, middleware::Next, response::IntoResponse,
};
/// Middleware for adding version information to each response's headers.
///
/// This middleware takes an incoming `Request` and a `Next` handler, which represents the
/// subsequent middleware or route in the chain. It then asynchronously runs the next handler,
/// obtaining the response. After receiving the response, it appends two headers:
/// - "Server": The name of the server extracted from the Cargo package name.
/// - "S-Version": The version of the server extracted from the Cargo package version.
pub async fn add_version(req: Request<Body>, next: Next) -> AppResult<impl IntoResponse> {
let mut res = next.run(req).await;
let headers = res.headers_mut();
headers.append(
"Server",
HeaderValue::from_str(env!("CARGO_PKG_NAME")).map_err(|err| anyhow!("{}", err))?,
);
Last active: a year ago
Vitest mock fn
import { existsSync, createReadStream, createWriteStream } from 'fs';
import { Readable, Writable } from 'stream';
import { afterEach, describe, it, vi } from 'vitest';
vi.mock('fs', async (importOriginal) => ({
...(await importOriginal<typeof import('fs')>()),
existsSync: vi.fn().mockImplementation(() => true),
createReadStream: vi.fn().mockImplementation(() => {
const stream = new Readable();
stream.push('test');
stream.push(null);
return stream;
}),
createWriteStream: vi.fn().mockImplementation(() => {
class MockWriter extends Writable {
_write(
chunk: string[] /* chunk: any,
encoding: BufferEncoding,
callback: (error?: Error | null | undefined) => void, */,
): void {
Last active: a year ago
WeChat and iOS WeChat regexp
export const isWeChat = () =>
/MicroMessenger/i.test(window.navigator.userAgent);
export const isWeChatSafari = navigator.userAgent.match(
/(?=iPhone|iPod)(?=.*(Safari|MicroMessenger))/i
);
Last active: 10 months ago
Rust git pre commit hooks
#!/bin/sh
set -eu
if ! cargo fmt -- --check; then
echo "There are some code style issues."
echo "Run cargo fmt first."
exit 1
fi
if ! cargo clippy --all-targets -- -D warnings; then
echo "There are some clippy issues."
exit 1
fi
exit 0
Last active: a year ago
Gitlab CI for rust
stages:
- build
variables:
APP_NAME: "cymo"
image: "rust:latest"
before_script:
- apt-get update -y
- mkdir $HOME/.cargo
- echo "[source.crates-io]" >> $HOME/.cargo/config
- echo "replace-with = 'ustc'" >> $HOME/.cargo/config
- echo "" >> $HOME/.cargo/config
- echo "[source.ustc]" >> $HOME/.cargo/config
- echo "registry = \"sparse+https://mirrors.ustc.edu.cn/crates.io-index/\"" >> $HOME/.cargo/config
- mkdir public
build:linux-gnu-amd64:
stage: build
Last active: a year ago
Trace layer for axum
use tower_http::trace::{
DefaultMakeSpan, DefaultOnBodyChunk, DefaultOnEos, DefaultOnFailure, DefaultOnRequest,
DefaultOnResponse, TraceLayer,
};
use tracing::Level;
/// Constructs a TraceLayer for Axum applications to enable logging and tracing of HTTP requests and responses.
///
/// The TraceLayer is a middleware layer that integrates with Tower HTTP's tracing capabilities.
/// It provides detailed information about the execution of HTTP requests and responses, allowing for
/// effective monitoring and debugging.
///
/// # Example
///
/// ```rust
/// Router::new()
/// .route("/", get(hello).post(hello))
/// .layer(tracing_layer())
/// }
/// ```