Page MenuHomeSealhub

collection-edit-form.ts
No OneTemporary

collection-edit-form.ts

import { toKebabCase, toPascalCase } from "js-convert-case";
import { formTemplate } from "../form.js";
import { curryImportPath } from "../../utils/import-path.js";
import _locreq from "locreq";
import extract_fields_from_collection from "../../utils/extract-fields-from-collection.js";
import { getFieldHandler } from "./shared-crud-form-fields.js";
export async function editItemFormTemplate(
edit_action_name: string,
newfilefullpath: string,
collection_name: string,
list_action: string
): Promise<string> {
const collection_fields = await extract_fields_from_collection(
collection_name
);
const importPath = curryImportPath(newfilefullpath);
const field_handler_results = await Promise.all(
collection_fields.map(async (field) => {
return getFieldHandler(collection_name, field, importPath);
})
);
return formTemplate(edit_action_name, newfilefullpath, {
postimport: `import {${toPascalCase(
collection_name
)}FormFields, ${toPascalCase(
collection_name
)}FormControls }from "../shared.js";
import { ${toPascalCase(collection_name)} } from "${importPath(
"src/back/collections/collections.js"
)}";
import { ${list_action}URL, ${edit_action_name}URL } from "${importPath(
"src/back/routes/urls.js"
)}";
import {tempstream} from "tempstream";
${Array.from(
new Set(field_handler_results.map(({ imports }) => imports.edit))
).join("\n")}
${
collection_fields.filter((e) => !e.is_required).length
? `import {withFallback} from "@sealcode/sealgen";`
: ""
}
`,
fields: `...${toPascalCase(collection_name)}FormFields`,
controls: `
new Controls.FormHeader("Edit ${toPascalCase(
collection_name
)}"),
...${toPascalCase(collection_name)}FormControls`,
can_access: `canAccess = async (ctx: Context) => {
const policy = ${toPascalCase(collection_name)}.getPolicy("edit");
const response = await policy.check(ctx.$context);
return { canAccess: response?.allowed || false, message: response?.reason || "" };
};`,
onsubmit: `
async onSubmit(ctx: Context) {
const data = await this.getParsedValues(ctx);
const id = await this.getID(ctx);
const {items: [item]} = await ctx.$app.collections["${toKebabCase(
collection_name
)}"]
.list(ctx.$context)
.ids([id])
.fetch();
if (!data) {
throw new Error("Error when parsing the form values");
}
${field_handler_results
.map((result) => result.pre_edit)
.filter((e) => e !== "")
.join("\n")}
item.setMultiple(
{
${field_handler_results
.filter((r) => !r.hide_sealious_value)
.map((result) => result.sealious_value(result))
.filter((e) => e != "")
.join(",\n")}
}
);
await item.save(ctx.$context);
${
field_handler_results
.map((result) => result.post_edit)
.filter((e) => e != "").length
? `// #### POST-EDIT ACTIONS ############`
: ""
}
${field_handler_results
.map((result) => result.post_edit)
.filter((e) => e != "")
.join("\n")}
}
`,
other_methods: `
async getID(ctx: Context): Promise<string>{
// trying to automatically guess which param is the one that represents the ID
// of the resource to edit.
// If sealgen got it wrong, just return the param name that should be used here instead
const param_name =
${edit_action_name}URL.params
.find(param => param.toLowerCase().includes("id"))
|| ${edit_action_name}URL.params[0]
const id = ctx.params[param_name];
if (!id) {
throw new Error("Missing URL parameter: " + param_name);
}
return id
}
`,
get_initial_values: `async getInitialValues(ctx: Context) {
const id = await this.getID(ctx);
const {
items: [item],
} = await ctx.$app.collections["${toKebabCase(collection_name)}"]
.list(ctx.$context)
.ids([id])
.attach({})
.fetch();
if (!item) {
throw new Error("Item with given id not found: " + id);
}
return {
${field_handler_results
.filter((r) => !r.hide_initial_value_edit)
.map(({ initial_value_edit, is_required, name }) => {
if (typeof initial_value_edit == "string") {
if (initial_value_edit == "") {
return "";
}
return `${name}: ${initial_value_edit}`;
}
const main_value = initial_value_edit.main_value;
if (!main_value) {
throw new Error(
"Missing main_value for initial_value_edit"
);
}
const { parsed_value, fallback_value } =
initial_value_edit;
if (is_required) {
return `${name}: ${parsed_value || main_value}`;
}
if (main_value && parsed_value && fallback_value) {
if (main_value == parsed_value) {
return `${name}: withFallback(${main_value}, ${fallback_value})`;
} else {
return `${name}: withFallback(${main_value}, ${parsed_value}, ${fallback_value})`;
}
} else {
console.error(initial_value_edit);
throw new Error(
"Missing field info for generating initial value"
);
}
})
.filter((e) => e.trim() !== "")
.join(",\n")}
};
}
`,
render: ` async render(ctx: Context, data: FormData, show_field_errors: boolean) {
return html(
ctx,
"Edit ${toPascalCase(collection_name)}",
tempstream/* HTML */ \` <div class="add-opinion-form">
<a class="" href="\${${list_action}URL}"
>← Back to ${collection_name} list</a
>
\${await super.render(ctx, data, show_field_errors)}
</div>\`
);
}`,
});
}

File Metadata

Mime Type
text/x-java
Expires
Tue, Dec 24, 14:05 (12 h, 29 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
557184
Default Alt Text
collection-edit-form.ts (5 KB)

Event Timeline