Skip to content

Commit

Permalink
Initial release of forcetrails/sobject-types package
Browse files Browse the repository at this point in the history
  • Loading branch information
rahulgawale committed Jun 13, 2024
0 parents commit 1db4a15
Show file tree
Hide file tree
Showing 15 changed files with 507 additions and 0 deletions.
21 changes: 21 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: CI
on:
push:
branches:
- "**"

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: 7
- uses: actions/setup-node@v3
with:
node-version: 16.x
cache: "pnpm"

- run: pnpm install --frozen-lockfile
- run: pnpm run lint && pnpm run build
36 changes: 36 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: Publish
on:
workflow_run:
workflows: [CI]
branches: [main]
types: [completed]

concurrency: ${{ github.workflow }}-${{ github.ref }}

permissions:
contents: write
pull-requests: write

jobs:
publish:
if: ${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: 7
- uses: actions/setup-node@v3
with:
node-version: 16.x
cache: "pnpm"

- run: pnpm install --frozen-lockfile
- name: Create Release Pull Request or Publish
id: changesets
uses: changesets/action@v1
with:
publish: pnpm run release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.changeset
dist
node_modules
package-lock.json
app.log
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"tabWidth": 2,
"useTabs": false,
"singleQuote": false
}
33 changes: 33 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@forcetrails/sobject-types",
"version": "0.0.1",
"description": "SObject and Field Types for Lightning Web Components TypeScript or JSDOC, to enable Type Safety and Intellisense",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"scope": "forcetrails",
"scripts": {
"build": "tsup",
"dev": "node dist/index.js"
},
"keywords": [
"lwc",
"typescript",
"salesforce",
"typings"
],
"author": "",
"license": "MIT",
"dependencies": {
"fs": "^0.0.1-security",
"morgan": "^1.10.0",
"path": "^0.12.7",
"winston": "^3.13.0"
},
"devDependencies": {
"@changesets/cli": "^2.27.5",
"@salesforce/ts-types": "^2.0.9",
"@types/node": "^20.14.2",
"tsup": "^8.1.0",
"typescript": "^5.4.5"
}
}
17 changes: 17 additions & 0 deletions src/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"sObjects": [
"Account",
"Contact",
"Lead",
"Case",
"Opportunity",
"OpportunityLineItem",
"Order",
"OrderItem",
"Quote",
"QuoteLine"
],
"sfPath": "sf",
"outputDir": "typings",
"defaultusername": "gunguna-dev"
}
37 changes: 37 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import * as fs from 'fs/promises';
import * as path from 'path';
import { Config, SfdxConfig } from './types';

// Define the path to the configuration file
const configFilePath = path.resolve(__dirname, 'config.json');
const sfdxConfigPath = path.resolve(__dirname, '.sfdx', 'sfdx-config.json');

let config: Config;
async function readConfigFile(filePath: string): Promise<Config> {
const data = await fs.readFile(filePath, 'utf8');
config = JSON.parse(data) as Config;
return config;
}

export async function getConfig() {
if (!config)
return await readConfigFile(configFilePath);
return config;
};

// sfdx config
let sfdxConfig: SfdxConfig;

async function readSfdxConfigFile(filePath: string): Promise<SfdxConfig> {
const data = await fs.readFile(filePath, 'utf8');
sfdxConfig = JSON.parse(data) as SfdxConfig;
return sfdxConfig;
}

export async function getSfdxConfig() {
if (!sfdxConfig)
return await readSfdxConfigFile(sfdxConfigPath);
return sfdxConfig;
};


117 changes: 117 additions & 0 deletions src/generator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
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`;

fields.forEach((field, i) => {
let fieldType: string;
const fieldName = field.name;

if (field.type === "picklist") {
fieldType = picklistTypes.typeNames.get(field.name) as string;
} else {
fieldType = mapFieldType(field.type);
}
// const optional = field.nillable ? '?' : '';
const readOnly = field.calculated || field.autoNumber ? "readonly " : "";
tsContent += `${additionalFieldInfo(field)}\n`;
tsContent += ` ${readOnly}${fieldName}?: ${fieldType};\n`;
});

tsContent += ` }
}\n`;

return tsContent;
}

function mapFieldType(salesforceType: string) {
switch (salesforceType) {
// picklist
case 'picklist':
// texts
case 'string':

case 'textarea':
case 'reference':
case 'id':
return 'string';

// boolean
case 'boolean':
return 'boolean';

// numbers
case 'int':
case 'currency':
case 'percent':
case 'number':
case 'double':
return 'number';

// dates
case 'date':
case 'datetime':
return 'Date';

// other
default:
return 'any';
}
}

function buildPicklist(field: SObjectFieldSchema) {
if (field.picklistValues) {
const active = field.picklistValues.filter(p => p.active === true).map(p => `'${p.value}'`);
return active.join(" | ");
}
return "";
}

function getPicklistTypes(objName: string, field: SObjectFieldSchema[]) {
const picklistTypes: PicklistResult = {
typeDefs: [],
typeNames: new Map()
};

field.filter(f => f.type === "picklist").forEach(f => {
let tName = `${objName}_${f.name}_Picklist`;
picklistTypes.typeDefs.push(`type ${tName} = ${buildPicklist(f)};`)
picklistTypes.typeNames.set(f.name, tName);
})

return picklistTypes;
}

function additionalFieldInfo(field: SObjectFieldSchema) {
let moreInfo = "";
moreInfo += field.calculated ? "\n @Formula" : "";
moreInfo += field.referenceTo && field.referenceTo.length > 0 ? `\n @Related To ${field.referenceTo?.join(",")}` : "";
moreInfo += field.relationshipName ? `\n @Relationship-Name ${field.relationshipName}` : "";
moreInfo += field.unique ? `\n @Unique` : "";
moreInfo += field.autoNumber ? `\n @Auto Number` : "";

const cmt = ` /**
@label ${field.label}
@type ${field.type}
@nillable ${field.nillable}
@Create ${field.createable}
@Update ${field.updateable}
${moreInfo}*/`;

return cmt;
}
15 changes: 15 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
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();
28 changes: 28 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { createLogger, format, transports } from 'winston';
const { combine, timestamp, json, colorize } = format;

// Custom format for console logging with colors
const consoleLogFormat = format.combine(
format.colorize(),
format.printf(({ level, message, timestamp }) => {
return `${level}: ${message}`;
})
);

// Create a Winston logger
const logger = createLogger({
level: 'info',
format: combine(
colorize(),
timestamp(),
json()
),
transports: [
new transports.Console({
format: consoleLogFormat
}),
new transports.File({ filename: 'app.log' })
],
});

export default logger;
Loading

0 comments on commit 1db4a15

Please sign in to comment.