added cleanup mutation (#157)
* added cleanup mutation * default to empty array
This commit is contained in:
@@ -3,6 +3,7 @@ import { BaseSQLDataSource } from './BaseSQLDataSource';
|
||||
import { camelcase } from 'stringcase';
|
||||
import slug from 'slug';
|
||||
import * as sql from './sql';
|
||||
import * as CONFIG from '../config';
|
||||
import {
|
||||
Product,
|
||||
ProductGroup,
|
||||
@@ -35,6 +36,8 @@ import { PrintProductDefaultsAPI } from './printproduct-defaults-api';
|
||||
import { GraphQLError } from 'graphql';
|
||||
import { MINUTE } from './utils';
|
||||
import { ScopeAccess, Scopes } from '../cognito/access-control';
|
||||
import { Interior } from '../types/interior-types';
|
||||
import { deleteFiles, listS3Files } from '../aws/s3';
|
||||
|
||||
export class ProductAPI extends BaseSQLDataSource {
|
||||
textsApi: TextsAPI;
|
||||
@@ -1005,6 +1008,52 @@ export class ProductAPI extends BaseSQLDataSource {
|
||||
return Promise.all(insertPromises);
|
||||
}
|
||||
|
||||
/**
|
||||
* @function cleanupInteriors
|
||||
* @description Removes all not used interiors from a product
|
||||
*/
|
||||
async cleanupInteriors(
|
||||
productId: number,
|
||||
currentInteriors: Interior[],
|
||||
): Promise<{ active: string[]; deleted: string[] }> {
|
||||
ScopeAccess.validate(this.user).all([
|
||||
Scopes.PRODUCTS_WRITE,
|
||||
Scopes.INTERIORS_WRITE,
|
||||
]);
|
||||
|
||||
// Get all interior files for product on s3
|
||||
const files = await listS3Files(
|
||||
CONFIG.imageBucket,
|
||||
`interiors/${productId}`,
|
||||
);
|
||||
|
||||
const shouldKeep = [];
|
||||
const shouldRemove = [];
|
||||
|
||||
// Convert to match key format from s3
|
||||
const currentUris = currentInteriors.map((item) => item.uri.substring(1));
|
||||
|
||||
// Go through all files on s3 and organize as delete or keep
|
||||
for (const file of files) {
|
||||
if (currentUris.includes(file.Key)) {
|
||||
shouldKeep.push(file.Key);
|
||||
} else {
|
||||
shouldRemove.push(file.Key);
|
||||
}
|
||||
}
|
||||
|
||||
// Setup all delete actions
|
||||
const deletePromises = shouldRemove.map((file) => {
|
||||
return deleteFiles(CONFIG.imageBucket, file);
|
||||
});
|
||||
|
||||
// Run all delete in parallell
|
||||
await Promise.all(deletePromises);
|
||||
|
||||
// Return what we did
|
||||
return { active: shouldKeep, deleted: shouldRemove };
|
||||
}
|
||||
|
||||
/**
|
||||
* @function setProportionsWarning
|
||||
* @description Sets propotion warning-values to a product
|
||||
|
||||
Reference in New Issue
Block a user