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

enable image key generation #229

Merged
merged 7 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions components/js-api-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -573,4 +573,20 @@ run();

A full example is here: https://github.com/CrystallizeAPI/libraries/blob/main/components/js-api-client/src/examples/dump-tenant.ts

## Image uploader

Uploading an image to Crystallize is a three step process:

- You first need to send a request to the PIM API to get a pre-signed URL to upload the file
- Then, you send another request to upload the file and receive a key
- Lastly, you can register the image in Crystallize using the key received in the previous step

To simplify this process, there is a _handleImageUpload_ function provided with the library. Here is how you would use it:

```javascript
const image = await handleImageUpload(path, crystallizeClient, 'tenantID');
```

This takes care of the first two steps, which means you receive a key you can then use to register your image in Crystallize.

[crystallizeobject]: crystallize_marketing|folder|625619f6615e162541535959
22 changes: 13 additions & 9 deletions components/js-api-client/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@crystallize/js-api-client",
"license": "MIT",
"version": "1.12.2",
"version": "1.13.0",
"author": "Crystallize <[email protected]> (https://crystallize.com)",
"contributors": [
"Sébastien Morel <[email protected]>"
Expand All @@ -20,17 +20,21 @@
"main": "dist/index.js",
"types": "dist/index.d.ts",
"devDependencies": {
"@tsconfig/node16": "^1.0.2",
"@types/node": "^17.0.23",
"@tsconfig/node16": "^16.1.1",
"@types/node": "^20.10.4",
"@types/node-fetch": "^2",
"jest": "^27.5.1"
"jest": "^29.7.0"
},
"dependencies": {
"dotenv": "^16.0.0",
"json-to-graphql-query": "^2.2.4",
"dotenv": "^16.3.1",
"json-to-graphql-query": "^2.2.5",
"mime-lite": "^1.0.3",
"node-fetch": "^2",
"tiny-invariant": "^1.2.0",
"typescript": "^4.6.3",
"zod": "^3.14.3"
"tiny-invariant": "^1.3.1",
"typescript": "^5.3.3",
"zod": "^3.22.4"
},
"browser": {
"fs": false
}
}
108 changes: 108 additions & 0 deletions components/js-api-client/src/core/uploadImage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import * as fs from 'fs';
import * as mime from 'mime-lite';
import { ClientInterface } from './client';

type ImageInputWithReferenceId = {
id: string;
filename: string;
mimeType: string;
};

type UploadHandler = ImageInputWithReferenceId & {
buffer: Buffer;
stats: fs.Stats;
apiClient: ClientInterface;
};

const MUTATION_UPLOAD_FILE = `#graphql
mutation UPLOAD_FILE ($tenantId: ID!, $filename: String!, $mimeType: String!) {
fileUpload {
generatePresignedRequest(
tenantId: $tenantId
filename: $filename
contentType: $mimeType
type: MEDIA
) {
url
fields {
name
value
}
}
}
}`;

export async function uploadImageToTenant({
id,
mimeType,
filename,
buffer,
stats,
apiClient,
}: UploadHandler): Promise<string | false> {
const signedRequestResult = await apiClient.pimApi(MUTATION_UPLOAD_FILE, {
tenantId: id,
filename,
mimeType,
});

const payload = signedRequestResult.fileUpload.generatePresignedRequest;
const formData: FormData = new FormData();
payload.fields.forEach((field: { name: string; value: string }) => {
formData.append(field.name, field.value);
});
formData.append('file', new Blob([buffer]));

const response = await fetch(payload.url, {
method: 'POST',
headers: new Headers({ 'Content-Length': String(stats.size) }),
body: formData,
});

return response.status === 201 ? (formData.get('key') as string) : false;
}

export async function handleImageUpload(
imagePath: string,
apiClient: ClientInterface,
tenantId?: string,
): Promise<string | boolean> {
if (!imagePath) {
return 'No image path provided';
}

const extension = imagePath.split('.').pop() as string;
const mimeType = mime.getType(extension);
const filename = imagePath.split('T/').pop() as string;

if (!mimeType) {
return 'Could not find mime type for file. Halting upload';
}

if (!mimeType.includes('image')) {
return 'File is not an image. Halting upload';
}

const stats = fs.statSync(imagePath);
const buffer = fs.readFileSync(imagePath);

const data: Omit<UploadHandler, 'id'> = {
mimeType,
filename,
stats,
buffer,
apiClient,
};

const tId = apiClient.config.tenantId ?? tenantId;
if (!tId) {
return 'No tenant id provided';
}

const imageKey = await uploadImageToTenant({
id: tId,
...data,
});

return imageKey;
}
1 change: 1 addition & 0 deletions components/js-api-client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export * from './types/address';
export * from './types/customer';
export * from './types/signature';
export * from './types/pricing';
export * from './core/uploadImage';

import { createClient } from './core/client';
import { createNavigationFetcher } from './core/navigation';
Expand Down
Loading