Skip to content

Commit

Permalink
refactor: factories in repository use name as id
Browse files Browse the repository at this point in the history
  • Loading branch information
Akryum committed Jan 8, 2024
1 parent 8b7d42b commit 2bc7b0e
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 42 deletions.
87 changes: 51 additions & 36 deletions packages/app/components/factory/FactoryForm.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang="ts" setup>
import { Dropdown } from 'floating-vue'
import type { ResourceFactory } from '@moquerie/core'
import type { ResourceFactory, ResourceSchemaType } from '@moquerie/core'
import type { FactoryData } from './formTypes.js'
import { useTagModel } from '~/utils/form.js'
Expand Down Expand Up @@ -29,12 +29,12 @@ const fakerLocaleOptions = computed(() => {
]
})
const { data: resourceType, refresh } = await useFetch(() => `/api/resources/${props.resourceName}`)
const { data: resourceType, refresh } = await useFetch<ResourceSchemaType>(() => `/api/resources/${props.resourceName}/`)
onWindowFocus(refresh)
function getStateInitialValues(factory = props.factory): FactoryData {
return {
name: factory?.name ?? `${props.resourceName} factory`,
name: factory?.name ?? `${props.resourceName}Factory`,
location: factory?.location ?? getDbLocationFromRouteQuery('factoryLocation') ?? 'local',
description: factory?.description ?? '',
tags: factory?.tags ? structuredClone(toRaw(factory.tags)) : [],
Expand Down Expand Up @@ -111,43 +111,54 @@ async function onSubmit() {
return
}
let factory: ResourceFactory
try {
let factory: ResourceFactory
if (props.factory) {
// Update factory
factory = await $fetch(`/api/factories/update`, {
method: 'PATCH',
body: {
id: props.factory.id,
...state.value,
},
})
toast.add({
id: 'factory-updated',
title: 'Factory updated!',
icon: 'i-ph-check-circle',
color: 'green',
})
if (props.factory) {
// Update factory
factory = await $fetch(`/api/factories/update`, {
method: 'PATCH',
body: {
id: props.factory.id,
...state.value,
},
})
toast.add({
id: 'factory-updated',
title: 'Factory updated!',
icon: 'i-ph-check-circle',
color: 'green',
})
}
else {
// Create factory
factory = await $fetch(`/api/factories/create`, {
method: 'POST',
body: state.value,
})
toast.add({
id: 'factory-created',
title: 'Factory created!',
icon: 'i-ph-check-circle',
color: 'green',
})
}
emit('complete', factory)
factoryStore.refreshFactories()
state.value = getStateInitialValues(factory)
}
else {
// Create factory
factory = await $fetch(`/api/factories/create`, {
method: 'POST',
body: state.value,
})
catch (e: any) {
toast.add({
id: 'factory-created',
title: 'Factory created!',
icon: 'i-ph-check-circle',
color: 'green',
id: 'factory-error',
title: 'Error',
description: e.message,
icon: 'i-ph-x-circle',
color: 'red',
})
}
emit('complete', factory)
factoryStore.refreshFactories()
state.value = getStateInitialValues(factory)
}
// Shortcuts
Expand Down Expand Up @@ -250,7 +261,11 @@ defineShortcuts({
@submit="onSubmit()"
>
<UFormGroup name="name" label="Factory name" required>
<UInput v-model="state.name" autofocus />
<UInput
v-model="state.name"
autofocus
placeholder="Examples: NewUserWithMessages, getNewUser, createEmptyItem"
/>
</UFormGroup>

<UFormGroup name="location" label="Location">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
<script lang="ts" setup>
import type { ResourceFactory } from '@moquerie/core'
const route = useRoute()
const router = useRouter()
const factoryStore = useFactoryStore()
const factory = await factoryStore.fetchFactory(route.params.factoryId as string)
const factory = shallowRef(await factoryStore.fetchFactory(route.params.factoryId as string))
function onComplete(data: ResourceFactory) {
factory.value = data
router.push({
name: 'db-factories-resourceName-view-factoryId',
params: {
resourceName: route.params.resourceName,
factoryId: data.id,
},
query: {
...route.query,
factoryLocation: data.location,
},
})
}
</script>

<template>
<FactoryForm
v-if="factory"
:resource-name="$route.params.resourceName as string"
:factory="factory"
@complete="factory = $event"
@complete="onComplete"
/>
</template>
10 changes: 8 additions & 2 deletions packages/app/server/api/factories/create.post.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import { nanoid } from 'nanoid'
import { getFactoryStorage } from '@moquerie/core'
import type { ResourceFactory } from '@moquerie/core'
import type { FactoryData } from '~/components/factory/formTypes.js'

export default defineEventHandler(async (event) => {
const body = await readBody(event)
const body: FactoryData = await readBody(event)
const storage = await getFactoryStorage()
const id = nanoid()
const id = body.location === 'repository' ? body.name : nanoid()

if (await storage.findById(id)) {
throw new Error(`Factory with id "${id}" already exists`)
}

const factory: ResourceFactory = {
id,
createdAt: new Date(),
Expand Down
21 changes: 20 additions & 1 deletion packages/app/server/api/factories/update.patch.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
import { nanoid } from 'nanoid'
import { getFactoryStorage } from '@moquerie/core'
import type { ResourceFactory } from '@moquerie/core'

export default defineEventHandler<{ body: ResourceFactory }>(async (event) => {
const body = await readBody(event)
const storage = await getFactoryStorage()

const factory = await storage.findById(body.id)
if (!factory) {
throw new Error(`Factory ${body.id} not found`)
}

if (factory.location !== body.location) {
if (body.location === 'local') {
// Override id with random one
await storage.remove(factory.id)
body.id = factory.id = nanoid()
}
else if (body.location === 'repository') {
// Use name as id
const name = body.name ?? factory.name
if (await storage.findById(name, 'repository')) {
throw new Error(`Factyory with name "${name}" already exists in repository`)
}
await storage.remove(factory.id)
body.id = factory.id = name
}
}
Object.assign(factory, body)
await storage.save(factory, factory.location)
return body
return factory
})
5 changes: 4 additions & 1 deletion packages/core/src/storage/mergedStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ export async function useMergedStorage<TData extends { id: string }>(options: Us
return data
}

async function findById(id: string) {
async function findById(id: string, location?: DBLocation) {
if (location) {
return storages[location].findById(id)
}
const localData = await storages.local.findById(id)
if (localData) {
return localData
Expand Down

0 comments on commit 2bc7b0e

Please sign in to comment.