shopping list

This commit is contained in:
cupcakearmy
2019-05-23 16:55:02 +02:00
parent 63d4b4a0fe
commit c50a37b08a
10 changed files with 207 additions and 4 deletions

24
api/src/entities/item.ts Normal file
View File

@@ -0,0 +1,24 @@
import { BaseEntity, Column, Entity, PrimaryColumn } from 'typeorm'
import UUID from 'uuid/v4'
@Entity()
export default class Item extends BaseEntity {
@PrimaryColumn()
id!: string
@Column()
text: string
@Column()
done: boolean
constructor(text: string, done: boolean = false) {
super()
this.id = UUID()
this.text = text
this.done = done
}
}

View File

@@ -1,13 +1,15 @@
import Router from 'koa-router'
import item from './item'
import purchase from './purchase'
import user from './user'
const r = new Router({
prefix: '/api'
prefix: '/api',
})
r.use(user.routes(), user.allowedMethods())
r.use(purchase.routes(), purchase.allowedMethods())
r.use(item.routes(), purchase.allowedMethods())
export default r

60
api/src/routes/item.ts Normal file
View File

@@ -0,0 +1,60 @@
import Router from 'koa-router'
import Item from '../entities/item'
import { withAuth } from '../lib/auth'
import { Success } from '../lib/responses'
const r = new Router({
prefix: '/items',
})
r.get('/', withAuth(async ctx => {
return Success(ctx, await Item.find())
}))
r.post('/', withAuth(async ctx => {
const { text, done } = ctx.request.body
return Success(ctx, await new Item(String(text), Boolean(done)).save())
}))
r.delete('/', withAuth(async ctx => {
return Success(ctx, await Item.clear())
}))
r.get('/:id', withAuth(async ctx => {
const { id } = ctx.params
const item = await Item.findOne(id)
// 404
if (!item) return
return Success(ctx, item)
}))
r.delete('/:id', withAuth(async ctx => {
const { id } = ctx.params
const item = await Item.findOne(id)
// 404
if (!item) return
await item.remove()
return Success(ctx)
}))
r.patch('/:id', withAuth(async ctx => {
const { id } = ctx.params
const item = await Item.findOne(id)
// 404
if (!item) return
const { text, done } = ctx.request.body
if (text !== undefined) item.text = String(text)
if (done !== undefined) item.done = Boolean(done)
return Success(ctx, await item.save())
}))
export default r

View File

@@ -5,6 +5,7 @@ import Parser from 'koa-bodyparser'
import { join } from 'path'
import { createConnection } from 'typeorm'
import Item from './entities/item'
import Purchase from './entities/purchase'
import User from './entities/user'
import { Config } from './lib/config'
@@ -15,7 +16,7 @@ import router from './routes'
createConnection({
type: 'sqlite',
database: join(process.cwd(), 'db.sqlite'),
entities: [User, Purchase],
entities: [User, Purchase, Item],
synchronize: true,
}).then(async () => {