Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitdb5b7b1

Browse files
committed
feat(action): add support for file uploads and helpers for working with files
1 parent52d6284 commitdb5b7b1

File tree

9 files changed

+355
-329
lines changed

9 files changed

+355
-329
lines changed

‎packages/action/package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
"devDependencies": {
1919
"@davstack/eslint-config":"workspace:*",
2020
"@davstack/tsconfig":"workspace:*",
21+
"@types/node":"^20.14.2",
2122
"@types/react":"^18.2.61",
2223
"@types/react-dom":"^18.2.19",
2324
"eslint":"^8.57.0",
@@ -29,6 +30,7 @@
2930
"access":"public"
3031
},
3132
"dependencies": {
33+
"object-to-formdata":"^4.5.1",
3234
"zod":"^3.22.4"
3335
}
3436
}

‎packages/action/src/action.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -231,21 +231,21 @@ export function createAction<
231231
};
232232

233233
/**
234-
* Invokes the resolver without parsing input/output
235-
* Useful for raw calls from the backend
234+
* Invokes the resolver without parsing input/output or middleware logic
236235
*/
237236
constrawCall=async(
238237
ctx:TContext,
239238
input:TInputSchemaextendsZodTypeAny ?zInfer<TInputSchema> :null
240239
)=>{
241-
returninvokeWithMiddleware(ctx,input);
240+
returndef.resolver({ input, ctx});
242241
};
243242

244243
/**
245244
* Invokes the resolver with parsing input/output and middleware logic
246245
* Useful for safe calls from the frontend
247246
*/
248-
constsafeCall=async(input:any)=>{
247+
constsafeCall=async(_input:any)=>{
248+
constinput=getMaybeFormDataValue(_input);
249249
constmaybeParsedInput=def.inputSchema
250250
?def.inputSchema.parse(input)
251251
:input;
@@ -262,3 +262,4 @@ export function createAction<
262262

263263
returnObject.assign(safeCall,def,{raw:rawCall});
264264
}
265+
import{getMaybeFormDataValue}from'./utils/form-data';

‎packages/action/src/index.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,7 @@
11
export*from'./action';
2+
export*from'./zod-file';
3+
import{serialize}from'object-to-formdata';
4+
5+
exportfunctionobjectToFormData<T>(obj:T):T{
6+
returnserialize(obj)asT;
7+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/* eslint-disable @typescript-eslint/no-non-null-assertion */
2+
3+
/**
4+
* CREDIT: https://github.com/trpc/trpc/blob/72c684683626b54907cccf8a12f3a3d726471652/packages/next/src/app-dir/formDataToObject.ts
5+
*/
6+
7+
exportfunctionisFormData(value:unknown):value isFormData{
8+
if(typeofFormData==='undefined'){
9+
// FormData is not supported
10+
returnfalse;
11+
}
12+
returnvalueinstanceofFormData;
13+
}
14+
15+
functionset(
16+
obj:Record<string,any>,
17+
path:string[]|string,
18+
value:unknown
19+
):void{
20+
if(typeofpath==='string'){
21+
path=path.split(/[\.\[\]]/).filter(Boolean);
22+
}
23+
24+
if(path.length>1){
25+
constp=path.shift()!;
26+
constisArrayIndex=/^\d+$/.test(path[0]!);
27+
obj[p]=obj[p]||(isArrayIndex ?[] :{});
28+
set(obj[p],path,value);
29+
return;
30+
}
31+
constp=path[0]!;
32+
if(obj[p]===undefined){
33+
obj[p]=value;
34+
}elseif(Array.isArray(obj[p])){
35+
obj[p].push(value);
36+
}else{
37+
obj[p]=[obj[p],value];
38+
}
39+
}
40+
41+
exportfunctionformDataToObject(formData:FormData){
42+
constobj:Record<string,unknown>={};
43+
44+
for(const[key,value]offormData.entries()){
45+
set(obj,key,value);
46+
}
47+
48+
returnobj;
49+
}
50+
51+
exportfunctiongetMaybeFormDataValue<T>(value:T|FormData):T{
52+
if(isFormData(value)){
53+
returnformDataToObject(value)asany;
54+
}
55+
56+
returnvalue;
57+
}
58+

‎packages/action/src/zod-file.ts‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
import{z}from'zod';
2+
3+
typeFileType=
4+
|'audio/*'
5+
|'video/*'
6+
|'application/*'
7+
|'image/*'
8+
|'text/*'
9+
|string[]
10+
|(string&{});
11+
12+
exportinterfaceZodFileOptions{
13+
type:FileType;
14+
maxSizeMb?:number;
15+
}
16+
17+
exportinterfaceZodFile{
18+
_type?:'ZodFile/Buffer'|'ZodFile/Blob'|'ZodFile/File';
19+
lastModified?:number;
20+
name?:string;
21+
size:number;
22+
type:string;
23+
arrayBuffer:()=>Promise<ArrayBuffer>;
24+
stream:()=>any;
25+
text:()=>Promise<string>;
26+
}
27+
28+
constMB=1024*1024;
29+
30+
exportfunctionzodFile(options:ZodFileOptions):z.ZodType<ZodFile>{
31+
const{ type, maxSizeMb=10}=options;
32+
letreceivedType='';
33+
34+
returnz
35+
.any()
36+
.refine(
37+
(file):file isFile|Blob|Buffer=>
38+
fileinstanceofFile||fileinstanceofBlob||Buffer.isBuffer(file),
39+
{message:'Invalid file provided.'}
40+
)
41+
.transform((file)=>{
42+
if(fileinstanceofFile){
43+
return{
44+
_type:'ZodFile/File'asconst,
45+
lastModified:file.lastModified,
46+
name:file.name,
47+
size:file.size,
48+
type:file.type,
49+
arrayBuffer:()=>file.arrayBuffer(),
50+
stream:()=>file.stream(),
51+
text:()=>file.text(),
52+
};
53+
}
54+
if(fileinstanceofBlob){
55+
return{
56+
_type:'ZodFile/Blob'asconst,
57+
lastModified:0,
58+
name:'',
59+
size:file.size,
60+
type:file.type,
61+
arrayBuffer:()=>file.arrayBuffer(),
62+
stream:()=>{
63+
thrownewError('Streaming not supported for Blob');
64+
},
65+
text:()=>file.text(),
66+
};
67+
}
68+
if(Buffer.isBuffer(file)){
69+
return{
70+
_type:'ZodFile/Buffer'asconst,
71+
lastModified:0,
72+
name:'',
73+
size:file.length,
74+
type:(fileasany).type??'',
75+
arrayBuffer:()=>Promise.resolve(file.buffer),
76+
stream:()=>{
77+
thrownewError('Streaming not supported for Buffer');
78+
},
79+
text:()=>Promise.resolve(file.toString()),
80+
};
81+
}
82+
thrownewError('Unexpected file type');
83+
})
84+
.refine(
85+
(file)=>{
86+
if(type==='*')returntrue;
87+
constacceptedTypes=getAcceptedFileTypes(type);
88+
constisAccepted=acceptedTypes.some((acceptedType)=>
89+
file.type.startsWith(acceptedType.replace('*',''))
90+
);
91+
if(!isAccepted)receivedType=file.type;
92+
returnisAccepted;
93+
},
94+
(file)=>({
95+
message:`Only${getFileTypeString(
96+
type
97+
)} files are accepted. Received:${receivedType||file.type}`,
98+
})
99+
)
100+
.refine((file)=>file.size<=maxSizeMb*MB,{
101+
message:`File size exceeds the limit of${maxSizeMb} MB.`,
102+
});
103+
}
104+
105+
functiongetAcceptedFileTypes(type:FileType):string[]{
106+
if(Array.isArray(type))returntype;
107+
return[type];
108+
}
109+
110+
functiongetFileTypeString(type:FileType):string{
111+
constacceptedTypes=getAcceptedFileTypes(type);
112+
if(acceptedTypes.length===0)return'NO FILE TYPES ARE ACCEPTED.';
113+
if(acceptedTypes.length===1)returnacceptedTypes[0]!;
114+
returnacceptedTypes.join(', ');
115+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import{describe,expect,test}from'vitest';
2+
import{action}from'../src';
3+
import{zodFile}from'../src/zod-file';
4+
5+
describe.only('action form data',()=>{
6+
constuploadFile=action()
7+
.input({
8+
file:zodFile({type:'123'}),
9+
})
10+
.mutation(async({ input, ctx})=>{
11+
return{ input, ctx};
12+
});
13+
14+
test('should accept audio file',async()=>{
15+
constfile=newBlob([],{type:'123'});
16+
constresult=awaituploadFile({ file});
17+
expect(result.input.file.type).toBe('123');
18+
});
19+
});

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp