All files / lib validation.ts

0% Statements 0/27
0% Branches 0/4
0% Functions 0/6
0% Lines 0/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167                                                                                                                                                                                                                                                                                                                                             
import { z } from "zod";
 
/**
 * Zodバリデーションスキーマ
 * APIリクエストの入力検証に使用
 */
 
// ===================================
// 共通バリデーション
// ===================================
 
const mongoIdSchema = z.string().regex(/^[0-9a-fA-F]{24}$/, "無効なIDです");
 
const tagsSchema = z
  .array(z.string().trim().min(1).max(20))
  .min(0)
  .max(10)
  .transform((tags) => tags.filter((tag, index, self) => self.indexOf(tag) === index)); // 重複削除
 
// ===================================
// 投稿関連バリデーション
// ===================================
 
export const createPostSchema = z.object({
  title: z
    .string()
    .trim()
    .min(1, "タイトルは必須です")
    .max(100, "タイトルは100文字以内で入力してください"),
  content: z
    .string()
    .trim()
    .min(10, "本文は10文字以上入力してください")
    .max(10000, "本文は10000文字以内で入力してください"),
  summary: z
    .string()
    .trim()
    .min(10, "要約は10文字以上入力してください")
    .max(300, "要約は300文字以内で入力してください"),
  categoryId: mongoIdSchema,
  tags: tagsSchema,
  visibility: z.enum(["public", "members_only", "private"]).describe("公開設定が不正です"),
});
 
export const updatePostSchema = z.object({
  title: z
    .string()
    .trim()
    .min(1, "タイトルは必須です")
    .max(100, "タイトルは100文字以内で入力してください")
    .optional(),
  content: z
    .string()
    .trim()
    .min(10, "本文は10文字以上入力してください")
    .max(10000, "本文は10000文字以内で入力してください")
    .optional(),
  summary: z
    .string()
    .trim()
    .min(10, "要約は10文字以上入力してください")
    .max(300, "要約は300文字以内で入力してください")
    .optional(),
  categoryId: mongoIdSchema.optional(),
  tags: tagsSchema.optional(),
  visibility: z
    .enum(["public", "members_only", "private"])
    .describe("公開設定が不正です")
    .optional(),
});
 
export const postListQuerySchema = z.object({
  page: z.coerce.number().int().min(1).default(1),
  limit: z.coerce.number().int().min(1).max(100).default(20),
  categoryId: mongoIdSchema.optional(),
  tags: z.string().optional(),
  visibility: z.enum(["public", "members_only", "private"]).optional(),
  authorId: mongoIdSchema.optional(),
  search: z.string().trim().max(100).optional(),
  sortBy: z.enum(["createdAt", "updatedAt", "viewCount"]).default("createdAt"),
  order: z.enum(["asc", "desc"]).default("desc"),
});
 
// ===================================
// コメント関連バリデーション
// ===================================
 
export const createCommentSchema = z.object({
  content: z
    .string()
    .trim()
    .min(1, "コメントは必須です")
    .max(1000, "コメントは1000文字以内で入力してください"),
});
 
export const commentListQuerySchema = z.object({
  page: z.coerce.number().int().min(1).default(1),
  limit: z.coerce.number().int().min(1).max(100).default(20),
});
 
// ===================================
// リアクション関連バリデーション
// ===================================
 
export const createReactionSchema = z.object({
  type: z.enum(["like", "helpful", "insightful", "thankful"]).describe("リアクションの種類が不正です"),
  postId: mongoIdSchema.optional(),
  commentId: mongoIdSchema.optional(),
}).refine(
  (data) => (data.postId && !data.commentId) || (!data.postId && data.commentId),
  {
    message: "postIdまたはcommentIdのいずれか一方を指定してください",
  }
);
 
// ===================================
// ユーザー関連バリデーション
// ===================================
 
export const updateUserProfileSchema = z.object({
  name: z
    .string()
    .trim()
    .min(1, "名前は必須です")
    .max(50, "名前は50文字以内で入力してください")
    .optional(),
  email: z.string().email("メールアドレスの形式が不正です").optional(),
});
 
// ===================================
// ヘルパー関数
// ===================================
 
/**
 * Zodスキーマで入力を検証し、パースされた結果を返す
 * @param schema - Zodスキーマ
 * @param data - 検証するデータ
 * @returns パース結果
 * @throws ZodError - バリデーションエラー時
 */
export function validate<T>(schema: z.ZodSchema<T>, data: unknown): T {
  return schema.parse(data);
}
 
/**
 * Zodスキーマで入力を検証し、成功/失敗を返す
 * @param schema - Zodスキーマ
 * @param data - 検証するデータ
 * @returns { success: true, data: T } | { success: false, error: ZodError }
 */
export function validateSafe<T>(
  schema: z.ZodSchema<T>,
  data: unknown
): { success: true; data: T } | { success: false; error: z.ZodError } {
  const result = schema.safeParse(data);
  return result;
}
 
/**
 * ObjectIdのバリデーション
 * @param id - 検証するID
 * @returns true if valid
 */
export function isValidMongoId(id: string): boolean {
  return mongoIdSchema.safeParse(id).success;
}