Skip to content

Commit

Permalink
added command line support
Browse files Browse the repository at this point in the history
  • Loading branch information
rahulgawale committed Jun 13, 2024
1 parent 6099a28 commit 8a0610a
Show file tree
Hide file tree
Showing 15 changed files with 269 additions and 56 deletions.
8 changes: 8 additions & 0 deletions .changeset/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Changesets

Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)

We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
11 changes: 11 additions & 0 deletions .changeset/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.0.1/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}
5 changes: 5 additions & 0 deletions .changeset/eleven-lies-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@forcetrails/sobject-types": major
---

This change uses sf cli plugin to run commands and generate types for Salesforce objects.
8 changes: 8 additions & 0 deletions .changeset/little-jars-jam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@forcetrails/sobject-types": major
---

Add command line support to the package. Added commands

#ftypes
ftype, with options like, list, config, add, and refresh
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
.changeset
dist
node_modules
package-lock.json
Expand Down
13 changes: 11 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
{
"name": "@forcetrails/sobject-types",
"version": "0.0.1",
"version": "0.1.0",
"description": "SObject and Field Types for Lightning Web Components TypeScript or JSDOC, to enable Type Safety and Intellisense",
"repository": {
"type": "git",
"url": "https://github.com/rahulgawale/sobject-types"
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"scope": "forcetrails",
"scripts": {
"build": "tsup",
"dev": "node dist/index.js"
},
"bin": {
"ftypes": "./dist/index.js"
},
"keywords": [
"lwc",
"typescript",
Expand All @@ -21,12 +28,14 @@
"fs": "^0.0.1-security",
"morgan": "^1.10.0",
"path": "^0.12.7",
"winston": "^3.13.0"
"winston": "^3.13.0",
"yargs": "^17.7.2"
},
"devDependencies": {
"@changesets/cli": "^2.27.5",
"@salesforce/ts-types": "^2.0.9",
"@types/node": "^20.14.2",
"@types/yargs": "^17.0.32",
"tsup": "^8.1.0",
"typescript": "^5.4.5"
}
Expand Down
2 changes: 1 addition & 1 deletion src/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"Order",
"OrderItem",
"Quote",
"QuoteLine"
"QuoteLineItem"
],
"sfPath": "sf",
"outputDir": "typings",
Expand Down
5 changes: 5 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as fs from 'fs/promises';
import * as path from 'path';
import { Config, SfdxConfig } from './types';
import { saveToFile } from './utils';

// Define the path to the configuration file
const configFilePath = path.resolve(__dirname, 'config.json');
Expand All @@ -19,6 +20,10 @@ export async function getConfig() {
return config;
};

export async function saveConfig(config: Config) {
await saveToFile(configFilePath, JSON.stringify(config));
}

// sfdx config
let sfdxConfig: SfdxConfig;

Expand Down
6 changes: 2 additions & 4 deletions src/generator.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import { PicklistResult, SObjectFieldSchema, SObjectSchema } from "./types";
import * as path from 'path';

export function generateTypes(sObjectDef: SObjectSchema) {
const a: SObjectSchema = {
fields: [],
name: "test",
label: "test"
}
const sObjectName = path.basename(sObjectDef.name, '.json');
const fields = sObjectDef.fields;

const picklistTypes = getPicklistTypes(sObjectDef.name, fields);

let tsContent = `
// picklist types
${picklistTypes.typeDefs.join('\n')}
declare module "@sobject-types/${sObjectName}"{\n
export interface ${sObjectName} {\n`;
declare module "@sobject-types/${sObjectDef.name}"{\n
export interface ${sObjectDef.name} {\n`;

fields.forEach((field, i) => {
let fieldType: string;
Expand Down
18 changes: 3 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,3 @@
import { saveObjectInfoToCache } from "./objectInfoFetcher";
import * as path from 'path';
import { getConfig } from "./config";
import logger from "./logger";

async function main() {
try {
const config = await getConfig();
saveObjectInfoToCache();
} catch (error) {
logger.error(error);
}
}

main();
#!/usr/bin/env node
import { router } from "./router";
router();
2 changes: 1 addition & 1 deletion src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ const logger = createLogger({
],
});

export default logger;
export default logger;
89 changes: 64 additions & 25 deletions src/objectInfoFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { exec } from 'child_process';
import * as path from 'path';
import { getConfig } from './config';
import { createDirectoryRecursive, saveToFile } from './utils';
import { SObjectSchema } from './types';
import { Config, SObjectSchema } from './types';
import { generateTypes } from './generator';
import logger from './logger';

Expand All @@ -21,53 +21,92 @@ function runCommand(command: string): Promise<any> {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
logger.error(error);
reject(new Error(`Command failed: ${error.message}`));
logger.error("runCommand error: " + error);
if (error.message.includes('is not recognized as an internal or external command')) {
logger.warn('⚠️ Make sure you have installed Salesforce CLI and PATH is set for that!');
}
reject("CLI Missing");
return;
}

if (stderr) {
logger.error("runCommand stderr: " + stderr);
}

const data = JSON.parse(stdout) as CommandOutPut;
if (data.status !== 0) {
logger.error("command status is " + data.status);
logger.error("runCommand: command status is " + data.status);
logger.warning(data.warning);
reject(null)
}
resolve(data.result);
});
});
}

async function describeSObject(sObjectName: string): Promise<SObjectSchema> {
export async function describeSObject(sObjectName: string): Promise<SObjectSchema> {
const config = await getConfig();
const cmd = `${config.sfPath} sobject describe --json --sobject ${sObjectName} --target-org ${config.defaultusername}`;
logger.info("command: " + cmd);

const schema = await runCommand(cmd) as SObjectSchema;
const filename = path.resolve(__dirname, config.outputDir, sObjectName + '.json');
// saveToFile(filename, JSON.stringify(schema));
const schema = await runCommand(cmd);
return schema;
}


export async function saveObjectInfoToCache() {
export async function generateSobjectTypes(config: Config, obj: string) {
try {
const objMetadata = await describeSObject(obj);

if (objMetadata) {
logger.info("Fetching Metadata: " + obj);
logger.info("name: " + objMetadata.name);
logger.info("#fields: " + objMetadata.fields.length);

const filename = path.resolve(__dirname, config.outputDir, obj + '.d.ts');
const types = generateTypes(objMetadata);
await saveToFile(filename, types);
return { success: true, message: `Successfully processed ${obj}` };
} else {
logger.error(`Could not fetch metadata for the object ${obj}, make sure the API Name is correct!`);
return { success: false, message: `Could not fetch metadata for ${obj}` };
}
} catch (err) {
logger.error(`Error while getting metadata for: ${obj}\nError: ${err}`);
return { success: false, message: `⚠️ Error fetching ${obj}, verify API Name` };
}
}

export async function generateAllTypes() {
try {
const config = await getConfig();
await createDirectoryRecursive(config.outputDir);

config.sObjects.forEach(async (obj) => {
try {
logger.info("Fetching Metadata: " + obj);
const objMetadata = await describeSObject(obj);
logger.info("name: " + objMetadata.name);
logger.info("#fields: " + objMetadata.fields.length);
const filename = path.resolve(__dirname, config.outputDir, obj + '.ts');
const types = generateTypes(objMetadata);
await saveToFile(filename, types);
} catch (err) {
console.log("Error while getting metadata for: " + obj + "\n", err)
for (const obj of config.sObjects) {
generateSobjectTypes(config, obj);
}
} catch (error) {
logger.error(`Error listing sObjects: ${(error as Error).message}`);
}
}

export async function generateAllTypesParallel() {
try {
const config = await getConfig();
await createDirectoryRecursive(config.outputDir, true);

const promises = config.sObjects.map(async (obj) => {
return generateSobjectTypes(config, obj);
});

const results = await Promise.all(promises);
results.forEach(result => {
if (result.success) {
logger.info(result.message);
} else {
logger.error(result.message);
}
})
});

} catch (error) {
console.error(`Error listing sObjects: ${(error as Error).message}`);
logger.error(`Error listing sObjects: ${(error as Error).message}`);
}
}
}
Loading

0 comments on commit 8a0610a

Please sign in to comment.