【问题标题】:what is the right way to create routes,dao,api?创建路由,dao,api的正确方法是什么?
【发布时间】:2022-06-28 22:21:03
【问题描述】:

这是我开发的第一个 koa 后端,我能知道它是对还是错

import { ObjectId } from 'mongodb'
import client from './index.js'

//create collection in database
const collection = client.db('exam').collection('user')

//add users
export const addUser = async (users) => {
  const result = await collection.insertOne(users)
  return result
}

//get users
export const getAll = async () => {
  const result = collection.find()
  const user = []
  await result.forEach((doc) => {
    const { _id, uname, email, phoneNo, address, password } = doc
    user.push({ _id, uname, email, phoneNo, address, password })
  })
  return user
}

//get user by id

export const getById = async (id) => {
  const result = await collection.findOne({ _id:new ObjectId(id) })
  return result
}

export const update = async (
  id,
  { uname, email, phoneNo, address, password }
) => {
  const result = await collection.replaceOne(
    { _id:new ObjectId(id) },
    { uname, email, phoneNo, address, password }
  )
  return result
}

export const removeById = async (id) => {
  await collection.deleteOne({ _id: ObjectId(id) })
}

export const login = async ({ email, password }) => {
  
   collection.findOne({ email: email }, function (err, result) {
    if (err)
      throw err
    console.log(email, password)
    if (result != null) {
      if (result.password === password) {
        console.log('granted')
        return 'granted'
      } else {
        return 'denied'
      }
    } else {
      console.log('Not Found')
      return 'Not found'
    }
  })
  
}
//subject amount
export const getAmount = async (sub) => {
  const result = collection.findOne(sub)
  const amount  = result
  return amount

}

API

import {
  addUser,
  getAll,
  getById,
  login,
  removeById,
  update,
} from '../dal/customer.dao.js'

//add user
export const regUser = async ({ uname, email, phoneNo, address, password }) => {
  const user = {
    uname,
    email,
    phoneNo,
    address,
    password,
  }
  const id = await addUser(user)
  return id
}

//get user
export const getUser = () => {
  return getAll()
}

//get user by Id

export const getUserrById =async (_id) => {
  return await getById(_id)
}

//delete user
export const deleteUser = async (id) => {
  return await removeById(id)
}
//update user
export const updateUser = async (
  id,
  { uname, email, phoneNo, address, password }
) => {
  return await update(id, { uname, email, phoneNo, address, password })
}

export const loginUser = async ({ email, password }) => {
  const credentials = {
    email,
    password,
    
  }
   await login(credentials).then((res) => {
      console.log(res)
    return res
  
  })
  //  return await a.then((res) => {
  //   console.log(res, 'res')
  //   return res
  // })
 
}
//subject
export const getSubAmount = (sub) => {
    return getAmount(sub)
}

路线

import Router from 'koa-router'
import { regUser, getUser, deleteUser, updateUser, getUserrById, loginUser} from '../api/customer.api.js'

//create the prefix to the url
const userRoutes = new Router({
  prefix: '/user',
})

//add user
userRoutes.post('/add', async (ctx) => {
  const data = ctx.request.body
  ctx.body = await regUser(data)
  ctx.status = 201
})

//get user
userRoutes.get('/', async (ctx) => {
  ctx.body = await getUser()
})

//get user by Id

userRoutes.get('/:id', async (ctx) => {
  const  _id  = ctx.params
  ctx.body = await getUserrById(_id)
})

//DELETE user
userRoutes.delete('/delete/:id', async (ctx) => {
  const id = ctx.params.id
  await deleteUser(id)
})

//Update user
userRoutes.put('/update/:id', async (ctx) => {
  const id = ctx.params.id
  let user = ctx.request.body
  user = await updateUser(id,user)
  ctx.response.status = 200
  ctx.body = user
})

userRoutes.post('/login', async (ctx) => {
  const credentials = ctx.request.body
  ctx.body = await loginUser(credentials).then((res) => {
    console.log(res,'ress')
    return res
  })
 
})


export default userRoutes

//subject
subjectRouter.get('/:name', async (ctx) => {
  
  const  sub  = ctx.params
  ctx.body=await getSubAmount(sub)
})

服务器

//import koa
import Koa from 'koa'

import cors from 'koa-cors'

//import bodyparser
import bodyParser from 'koa-bodyparser'


//routes
import userRoutes from './routes/user.routes.js'
import courseRoutes from './routes/course.routes.js'
import subjectRoutes from './routes/subject.routes.js'
//listen to port
const PORT = process.env.PORT || 5000

//database connection
import './dal/index.js'

//create new koa app
const app = new Koa()

app.use(bodyParser())
app.use(cors())

app.use(userRoutes.routes()).use(userRoutes.allowedMethods())
app.use(courseRoutes.routes()).use(courseRoutes.allowedMethods())
app.use(subjectRoutes.routes()).use(subjectRoutes.allowedMethods())

app.listen(PORT, () => {
  console.log(`server is running in on port : ${PORT}`)
})

Express 背后的团队创建了一个名为 Koa 的新 Web 框架。 Koa 承诺提供更小、更有表现力和更健壮的 Web 应用程序基础。 Koa 对异步函数的使用允许您避免回调并显着改进错误处理。也用于设计 API。许多功能可通过插件获得

【问题讨论】:

    标签: reactjs mongodb react-router koa koa-router


    【解决方案1】:

    代码是正确的,但最好这样编码

    const users = require('./index').db('store').collection('user')
    const ObjectId = require('mongodb').ObjectId
    
    const save = async ({ username, email, phoneNo, address, password }) => {
      const result = await users.insertOne({
        username,
        email,
        phoneNo,
        address,
        password,
      })
      return result
    }
    
    const getAll = async () => {
      const cursor = await users.find()
      return cursor.toArray()
    }
    
    const getById = async (id) => {
      return await users.findOne({ _id: ObjectId(id) })
    }
    
    const update = async (id, { username, email, phoneNo, address, password }) => {
      const result = await users.replaceOne(
        { _id: ObjectId(id) },
        { username, email, phoneNo, address, password }
      )
      return result
    }
    
    const removeById = async (id) => {
      await users.deleteOne({ _id: ObjectId(id) })
    }
    
    const login = async ({ email, password }) => {
      await users.findOne({ email: email }, function (err, result) {
        if (err) throw err
        if (result != null) {
          if (result.password === password) {
            console.log('granted')
            return 'granted'
          } else {
            console.log('denied')
            return 'denied'
          }
        } else {
          console.log('Not Found')
          return 'Not Found'
        }
      })
    }
    
    module.exports = { save, getAll, getById, removeById, update, login }
    
    

    API

    const {
      save,
      getAll,
      getById,
      removeById,
      update,
      login,
    } = require('../dal/users.dao')
    
    const registerUser = async ({
      username,
      email,
      phoneNo,
      address,
      password,
    }) => {
      const user = {
        username,
        email,
        phoneNo,
        address,
        password,
      }
      return await save(user)
    }
    
    const getUsers = async () => {
      return await getAll()
    }
    
    const getUser = async (id) => {
      return await getById(id)
    }
    
    const deleteUser = async (id) => {
      return await removeById(id)
    }
    
    const updateUser = async (
      id,
      { username, email, phoneNo, address, password }
    ) => {
      return await update(id, { username, email, phoneNo, address, password })
    }
    
    const loginUser = async ({ email, password }) => {
      const credentials = {
        email,
        password,
      }
      return await login(credentials)
    }
    
    module.exports = {
      registerUser,
      getUsers,
      getUser,
      deleteUser,
      updateUser,
      loginUser,
    }
    
    

    路线

    const Router = require('@koa/router')
    const {
      registerUser,
      getUsers,
      getUser,
      deleteUser,
      updateUser,
      loginUser,
    } = require('../api/users.api')
    
    const router = new Router({
      prefix: '/users',
    })
    
    //GET
    router.get('/', async (ctx) => {
      ctx.body = await getUsers()
    })
    
    //POST
    router.post('/', async (ctx) => {
      let user = ctx.request.body
      user = await registerUser(user)
      ctx.response.status = 200
      ctx.body = user
    })
    
    //GET one user
    router.get('/:id', async (ctx) => {
      const id = ctx.params.id
      ctx.body = await getUser(id)
    })
    
    //DELETE user
    router.delete('/:id', async (ctx) => {
      const id = ctx.params.id
      await deleteUser(id)
    })
    
    //Update user
    router.put('/:id', async (ctx) => {
      const id = ctx.params.id
      let user = ctx.request.body
      user = await updateUser(id, user)
      ctx.response.status = 200
      ctx.body = user
    })
    
    router.post('/login', async (ctx) => {
      const credentials = ctx.request.body
      ctx.body = await loginUser(credentials).then((res) => {
        return res
      })
    })
    
    module.exports = router
    
    

    server.js

    const Koa = require('Koa')
    const bodyParser = require('koa-bodyparser')
    const cors = require('@koa/cors')
    
    const app = new Koa()
    app.use(bodyParser())
    app.use(cors())
    const PORT = 5000
    
    const userRoutes = require('./routes/users.routes')
    app.use(userRoutes.routes()).use(userRoutes.allowedMethods())
    
    app.listen(PORT, (err) => {
      if (err) {
        console.log(err)
        return
      }
      console.log(`Application is running on ${PORT}`)
    })
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 2015-02-10
      • 2012-06-18
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多