1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JSforceとレコードの型

Last updated at Posted at 2020-03-08

 初投稿です。JSforce 2.0でのレコードの型が気になりました。いずれドキュメントなどで公開されるのだと思いますが私は今知りたかったので……。

環境は次の通りです。

  • JSforce 2.0.0-alpha.11
  • TypeScript 3.8.3

 あるオブジェクトのレコードの型は SObjectRecord とスキーマとオブジェクト名で表せるようです。

type Account = SObjectRecord<StandardSchema, "Account">;

const accounts: Account[] = await conn
  .sobject("Account")
  .find();

const id: string = accounts[0].Id;

項目を絞るときはそのパターンを追加します。

type Account = SObjectRecord<StandardSchema, "Account", "Id" | "Name">;

const accounts: Account[] = await conn
  .sobject("Account")
  .find(null, ["Id", "Name"]);

const name: string = accounts[0].Name;

親のレコードを含むときも同様です。

type Account = SObjectRecord<StandardSchema, "Account", "Id" | "Name" | { Owner: "Id" | "Name" }>;

const accounts: Account[] = await conn
  .sobject("Account")
  .find(null, ["Id", "Name", "Owner.Id", "Owner.Name"]);

const ownerId: string = accounts[0].Owner.Id;

子のレコードを含むときは SObjectChildRelationshipProp で拡張します。

type Contact = SObjectRecord<StandardSchema, "Contact", "Id" | "Name">;
type Account = SObjectRecord<StandardSchema, "Account", "Id" | "Name"> &
  SObjectChildRelationshipProp<"Contacts", Contact>;

const accounts: Account[] = await conn
  .sobject("Account")
  .find(null, ["Id", "Name"])
  .include("Contacts", null, ["Id", "Name"])
  .end();

const contactIds: string[] = accounts[0].Contacts?.records.map(contact => contact.Id) ?? [];

これで大体のレコードに型を付けられそうです。やっていきましょう。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?