| 59 | } |
| 60 | |
| 61 | export async function createShip(request: Request) { |
| 62 | const endTime = Date.now() + getDelay(request) |
| 63 | const formData = await request.formData() |
| 64 | const name = formData.get('name') |
| 65 | const image = formData.get('image') |
| 66 | const topSpeed = Number(formData.get('topSpeed')) |
| 67 | invariantResponse(typeof name === 'string' && name, 'Name incorrect type') |
| 68 | invariantResponse(!image || image instanceof File, 'Image incorrect type') |
| 69 | invariantResponse( |
| 70 | typeof topSpeed === 'number' && topSpeed, |
| 71 | 'Top speed incorrect type', |
| 72 | ) |
| 73 | |
| 74 | // this is mostly for testing purposes. In the real app the image is required |
| 75 | let imageName: string | null = null |
| 76 | if (image instanceof File && image.name) { |
| 77 | imageName = image.name |
| 78 | const filePath = atRoot('public', 'img', 'custom-ships', image.name) |
| 79 | |
| 80 | await fs.promises.mkdir(path.dirname(filePath), { recursive: true }) |
| 81 | await fs.promises.writeFile( |
| 82 | filePath, |
| 83 | Buffer.from(await image.arrayBuffer()), |
| 84 | ) |
| 85 | } |
| 86 | |
| 87 | const ship = { |
| 88 | name, |
| 89 | image: imageName |
| 90 | ? `/img/custom-ships/${imageName}` |
| 91 | : `/img/ships/battleship.webp`, |
| 92 | topSpeed, |
| 93 | weapons: [], |
| 94 | } |
| 95 | |
| 96 | shipData.push(ship) |
| 97 | |
| 98 | await new Promise((resolve) => setTimeout(resolve, endTime - Date.now())) |
| 99 | |
| 100 | return new Response('OK', { status: 201 }) |
| 101 | } |