Nodejs Development

作者 mindrally97184105b5da无许可证269 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5周前更新

Node.js development guidelines covering Payload CMS, Vue.js with TypeScript, and general TypeScript best practices

AI 生成的概览

Node.js 与 TypeScript 开发指南,涵盖 Payload CMS、Vue.js 组件与 Zod 校验模式。

功能
提供 Node.js 结合 TypeScript 开发的参考指引与代码示例。内容涵盖 Next.js 中的 Payload CMS 集合与 API 路由、Vue.js 组件、组合式函数与 Pinia store、Zod 模式校验与 Express 中间件,以及错误处理、异步与测试的一般实践。产出的是说明性模式与代码片段,而非可运行工具。
适用场景
适用于编写或审查 Node.js 项目中的 TypeScript 代码,尤其是使用 Payload CMS、Next.js、Vue.js 或 Zod 的场景。适合希望采用成熟模式处理集合、组件、store 与校验的开发者。
运行要求
除智能体外无需其他条件;仅为说明文档,不附带脚本。

Node.js Development Guidelines

You are an expert in Node.js development with TypeScript, covering various frameworks and patterns.

Payload CMS with Next.js

Project Setup

project/├── src/│   ├── app/              # Next.js app directory│   ├── collections/      # Payload collections│   ├── blocks/          # Custom blocks│   ├── fields/          # Custom fields│   └── access/          # Access control functions├── payload.config.ts    # Payload configuration└── next.config.js       # Next.js configuration

Collection Definition

typescript
import { CollectionConfig } from 'payload/types';
const Posts: CollectionConfig = {  slug: 'posts',  admin: {    useAsTitle: 'title',  },  access: {    read: () => true,    create: ({ req: { user } }) => Boolean(user),    update: ({ req: { user } }) => Boolean(user),    delete: ({ req: { user } }) => Boolean(user),  },  fields: [    {      name: 'title',      type: 'text',      required: true,    },    {      name: 'content',      type: 'richText',    },    {      name: 'publishedDate',      type: 'date',    },  ],};
export default Posts;

API Routes

typescript
// app/api/posts/route.tsimport { getPayloadClient } from '@/lib/payload';
export async function GET() {  const payload = await getPayloadClient();  const posts = await payload.find({    collection: 'posts',    limit: 10,  });  return Response.json(posts);}

Vue.js with TypeScript

Component Structure

vue
<script setup lang="ts">import { ref, computed, onMounted } from 'vue';
interface User {  id: number;  name: string;  email: string;}
const props = defineProps<{  userId: number;}>();
const emit = defineEmits<{  (e: 'update', user: User): void;}>();
const user = ref<User | null>(null);const isLoading = ref(false);
const displayName = computed(() => user.value?.name ?? 'Unknown');
async function fetchUser() {  isLoading.value = true;  try {    const response = await fetch(`/api/users/${props.userId}`);    user.value = await response.json();  } finally {    isLoading.value = false;  }}
onMounted(fetchUser);</script>
<template>  <div v-if="isLoading">Loading...</div>  <div v-else-if="user">    <h2>{{ displayName }}</h2>    <p>{{ user.email }}</p>  </div></template>

Composables

typescript
// composables/useApi.tsimport { ref } from 'vue';
export function useApi<T>(url: string) {  const data = ref<T | null>(null);  const error = ref<Error | null>(null);  const isLoading = ref(false);
  async function execute() {    isLoading.value = true;    error.value = null;
    try {      const response = await fetch(url);      if (!response.ok) throw new Error('Request failed');      data.value = await response.json();    } catch (e) {      error.value = e as Error;    } finally {      isLoading.value = false;    }  }
  return { data, error, isLoading, execute };}

Pinia Store

typescript
// stores/user.tsimport { defineStore } from 'pinia';
interface UserState {  user: User | null;  isAuthenticated: boolean;}
export const useUserStore = defineStore('user', {  state: (): UserState => ({    user: null,    isAuthenticated: false,  }),
  getters: {    displayName: (state) => state.user?.name ?? 'Guest',  },
  actions: {    async login(credentials: LoginCredentials) {      const user = await authService.login(credentials);      this.user = user;      this.isAuthenticated = true;    },
    logout() {      this.user = null;      this.isAuthenticated = false;    },  },});

TypeScript with Zod

Schema Definition

typescript
import { z } from 'zod';
const UserSchema = z.object({  id: z.number(),  name: z.string().min(1),  email: z.string().email(),  role: z.enum(['user', 'admin']),  createdAt: z.date(),});
type User = z.infer<typeof UserSchema>;
const CreateUserSchema = UserSchema.omit({ id: true, createdAt: true });type CreateUserInput = z.infer<typeof CreateUserSchema>;

Validation

typescript
function createUser(input: unknown): User {  const validatedInput = CreateUserSchema.parse(input);  // Input is now typed as CreateUserInput  return {    ...validatedInput,    id: generateId(),    createdAt: new Date(),  };}
// Safe parsing (doesn't throw)function validateUser(input: unknown) {  const result = UserSchema.safeParse(input);  if (!result.success) {    console.error(result.error.issues);    return null;  }  return result.data;}

API Validation Middleware

typescript
import { z } from 'zod';import { Request, Response, NextFunction } from 'express';
function validate<T extends z.ZodSchema>(schema: T) {  return (req: Request, res: Response, next: NextFunction) => {    const result = schema.safeParse(req.body);    if (!result.success) {      return res.status(400).json({ errors: result.error.issues });    }    req.body = result.data;    next();  };}
// Usageapp.post('/users', validate(CreateUserSchema), createUserHandler);

General Best Practices

Error Handling

  • Use custom error classes
  • Implement global error handlers
  • Log errors with context
  • Return appropriate status codes

Async Patterns

  • Use async/await consistently
  • Handle promise rejections
  • Implement proper timeouts
  • Use Promise.all for parallel operations

Testing

  • Write unit tests for utilities
  • Integration tests for APIs
  • Use test fixtures
  • Mock external dependencies

来源与署名

来源:mindrally/skills位于nodejs-development提交9718410

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架