Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ PATCH items (CRUD) #267

Merged
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/stale-carrots-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'manifest': minor
'@mnfst/sdk': minor
---

Added PATCH requests for item update
22 changes: 22 additions & 0 deletions .github/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name-template: 'v$NEXT_PATCH_VERSION'
tag-template: 'v$NEXT_PATCH_VERSION'
categories:
- title: '🚀 Features'
labels:
- enhancement
- title: '🐛 Bug Fixes'
labels:
- bug
- title: '🛠 Maintenance'
labels:
- chore
- refactor
- tests
- dependencies
change-template: '- $TITLE (#$NUMBER)'
no-changes-template: '- No changes'

template: |
## What's Changed

$CHANGES
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Release
name: Publish

on:
push:
Expand Down
30 changes: 30 additions & 0 deletions .github/workflows/release-drafter.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Release Drafter

on:
push:
tags:
- 'manifest@*.*.*' # Match tags for "manifest"
- '@mnfst/sdk@*.*.*' # Match tags for "@mnfst/sdk"
- 'add-manifest@*.*.*' # Match tags for "add-manifest"
workflow_dispatch: # Allow manual triggering of the workflow

permissions:
contents: write
pull-requests: write

jobs:
release:
runs-on: ubuntu-latest

steps:
# Step 1: Checkout the repository
- name: Checkout repository
uses: actions/checkout@v3

# Step 2: Run Release Drafter to draft and publish the release
- name: Draft and Publish Release
uses: release-drafter/release-drafter@v5
with:
config-name: release.yml
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
27 changes: 26 additions & 1 deletion packages/core/manifest/e2e/tests/collection-crud.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,36 @@ describe('Collection CRUD (e2e)', () => {

expect(updatedResponse.status).toBe(200)
expect(updatedResponse.body).toMatchObject({
...dummyDog,
name: newName
})
})

it('PATCH /collections/:entity/:id', async () => {
const postResponse = await global.request
.post('/collections/dogs')
.send(dummyDog)

const newAge = 6

const response = await global.request
.patch(`/collections/dogs/${postResponse.body.id}`)
.send({
age: newAge
})

expect(response.status).toBe(200)

const updatedResponse = await global.request.get(
`/collections/dogs/${postResponse.body.id}`
)

expect(updatedResponse.status).toBe(200)
expect(updatedResponse.body).toMatchObject({
...dummyDog,
age: newAge
})
})

it('DELETE /collections/:entity/:id', async () => {
const response = await global.request.delete('/collections/dogs/1')

Expand Down
2 changes: 1 addition & 1 deletion packages/core/manifest/e2e/tests/single-crud.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ describe('Single CRUD (e2e)', () => {
})
})

describe('PUT /collections/:entity', () => {
describe('PUT /singles/:entity', () => {
it('can update a single entity', async () => {
const newTitle: string = 'Contact Us'

Expand Down
2 changes: 1 addition & 1 deletion packages/core/manifest/e2e/tests/validation.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ describe('Validation (e2e)', () => {

const updateResponse = await global.request
.put('/collections/super-users/1')
.send({ name: 'new name' })
.send({ name: 'new name', email: 'example2@manifest.build' })

expect(badCreateResponse.status).toBe(400)
expect(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
Get,
Param,
ParseIntPipe,
Patch,
Post,
Put,
Query,
Expand Down Expand Up @@ -86,12 +87,27 @@ export class CollectionController {

@Put(':entity/:id')
@Rule('update')
update(
@Param('entity') entity: string,
put(
@Param('entity') entitySlug: string,
@Param('id', ParseIntPipe) id: number,
@Body() entityDto: Partial<BaseEntity>
@Body() itemDto: Partial<BaseEntity>
): Promise<BaseEntity> {
return this.crudService.update({ entitySlug, id, itemDto })
}

@Patch(':entity/:id')
@Rule('update')
patch(
@Param('entity') entitySlug: string,
@Param('id', ParseIntPipe) id: number,
@Body() itemDto: Partial<BaseEntity>
): Promise<BaseEntity> {
return this.crudService.update(entity, id, entityDto)
return this.crudService.update({
entitySlug,
id,
itemDto,
partialReplacement: true
})
}

@Delete(':entity/:id')
Expand Down
23 changes: 19 additions & 4 deletions packages/core/manifest/src/crud/controllers/single.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
Get,
NotFoundException,
Param,
Patch,
Put,
Req,
UseGuards
Expand Down Expand Up @@ -55,10 +56,24 @@ export class SingleController {

@Put(':entity')
@Rule('update')
update(
@Param('entity') entity: string,
@Body() entityDto: Partial<BaseEntity>
put(
@Param('entity') entitySlug: string,
@Body() itemDto: Partial<BaseEntity>
): Promise<BaseEntity> {
return this.crudService.update({ entitySlug, id: 1, itemDto })
}

@Patch(':entity')
@Rule('update')
patch(
@Param('entity') entitySlug: string,
@Body() itemDto: Partial<BaseEntity>
): Promise<BaseEntity> {
return this.crudService.update(entity, 1, entityDto)
return this.crudService.update({
entitySlug,
id: 1,
itemDto,
partialReplacement: true
})
}
}
45 changes: 35 additions & 10 deletions packages/core/manifest/src/crud/services/crud.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,11 +274,27 @@ export class CrudService {
return entityRepository.save({})
}

async update(
entitySlug: string,
id: number,
/*
* Updates an item doing a FULL REPLACEMENT of the item properties and relations unless partialReplacement is set to true.
*
* @param entitySlug the entity slug.
* @param id the item id.
* @param itemDto the item dto.
* @param partialReplacement whether to do a partial replacement.
*
* @returns the updated item.
*/
async update({
entitySlug,
id,
itemDto,
partialReplacement
}: {
entitySlug: string
id: number
itemDto: Partial<BaseEntity>
): Promise<BaseEntity> {
partialReplacement?: boolean
}): Promise<BaseEntity> {
const entityManifest: EntityManifest =
this.entityManifestService.getEntityManifest({
slug: entitySlug,
Expand All @@ -290,6 +306,10 @@ export class CrudService {

const item: BaseEntity = await entityRepository.findOne({ where: { id } })

if (!item) {
throw new NotFoundException('Item not found')
}

const relationItems: { [key: string]: BaseEntity | BaseEntity[] } =
await this.relationshipService.fetchRelationItemsFromDto(
itemDto,
Expand All @@ -298,14 +318,19 @@ export class CrudService {
.filter((r) => r.type !== 'many-to-many' || r.owningSide)
)

if (!item) {
throw new NotFoundException('Item not found')
// On partial replacement, only update the provided props.
if (partialReplacement) {
itemDto = { ...item, ...itemDto }

// Remove undefined values to keep the existing values.
Object.keys(relationItems).forEach((key: string) => {
if (relationItems[key] === undefined) {
delete relationItems[key]
}
})
}

const updatedItem: BaseEntity = entityRepository.create({
...item,
...itemDto
} as BaseEntity)
const updatedItem: BaseEntity = entityRepository.create({ id, ...itemDto })

// Hash password if it exists.
if (entityManifest.authenticable && itemDto.password) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { EntityManifestService } from '../../manifest/services/entity-manifest.s

describe('CollectionController', () => {
let controller: CollectionController
let crudService: CrudService

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
Expand All @@ -16,14 +17,18 @@ describe('CollectionController', () => {
{
provide: AuthService,
useValue: {
isReqUserAdmin: jest.fn()
isReqUserAdmin: jest.fn(() => Promise.resolve(false))
}
},
{
provide: CrudService,
useValue: {
findOne: jest.fn(),
update: jest.fn()
findAll: jest.fn(),
findSelectOptions: jest.fn(),
store: jest.fn(),
update: jest.fn(),
delete: jest.fn()
}
},
{
Expand All @@ -48,9 +53,99 @@ describe('CollectionController', () => {
}).compile()

controller = module.get<CollectionController>(CollectionController)
crudService = module.get<CrudService>(CrudService)
})

it('should be defined', () => {
expect(controller).toBeDefined()
})

it('should call crudService.findAll', async () => {
const entitySlug = 'cats'
const queryParams = {}
const req = {} as any

await controller.findAll(entitySlug, queryParams, req)

expect(crudService.findAll).toHaveBeenCalledWith({
entitySlug,
queryParams,
fullVersion: false
})
})

it('should call crudService.findSelectOptions', async () => {
const entitySlug = 'cats'
const queryParams = {}

await controller.findSelectOptions(entitySlug, queryParams)

expect(crudService.findSelectOptions).toHaveBeenCalledWith({
entitySlug,
queryParams
})
})

it('should call crudService.findOne', async () => {
const entitySlug = 'cats'
const id = 1
const queryParams = {}
const req = {} as any

await controller.findOne(entitySlug, id, queryParams, req)

expect(crudService.findOne).toHaveBeenCalledWith({
entitySlug,
id,
queryParams,
fullVersion: false
})
})

it('should call crudService.store', async () => {
const entity = 'cats'
const itemDto = {}

await controller.store(entity, itemDto)

expect(crudService.store).toHaveBeenCalledWith(entity, itemDto)
})

it('should call crudService.update', async () => {
const entitySlug = 'cats'
const id = 1
const itemDto = {}

await controller.put(entitySlug, id, itemDto)

expect(crudService.update).toHaveBeenCalledWith({
entitySlug,
id,
itemDto: itemDto
})
})

it('should call crudService.update with partialReplacement', async () => {
const entitySlug = 'cats'
const id = 1
const itemDto = {}

await controller.patch(entitySlug, id, itemDto)

expect(crudService.update).toHaveBeenCalledWith({
entitySlug,
id,
itemDto: itemDto,
partialReplacement: true
})
})

it('should call crudService.delete', async () => {
const entitySlug = 'cats'
const id = 1

await controller.delete(entitySlug, id)

expect(crudService.delete).toHaveBeenCalledWith(entitySlug, id)
})
})
Loading
Loading