Skip to content

Sys.Microsoft

Sys.Microsoft gives server-side code access to Microsoft 365 and Microsoft Entra ID through the Microsoft Graph API. Two clients cover the common cases:

  • SimpleGraphApplicationClient acts as an app registration, with application permissions (client credentials).
  • SimpleGraphUserClient acts on behalf of a user who signed in to Lowgile through a Microsoft identity provider, with delegated permissions.

Both clients expose Graph resources as list clients and item clients, which build the Graph requests for you. Sys.Microsoft also re-exports the Microsoft libraries the clients are built on.

Availability: Server

export * as AzureIdentity from '@azure/identity'

The Azure Identity library (@azure/identity 4.13.3), re-exported as-is. It provides credential classes that obtain Microsoft Entra ID tokens.

const credential = new Sys.Microsoft.AzureIdentity.ClientSecretCredential(tenantId, clientId, clientSecret)

Type: module namespace of @azure/identity · Availability: Server

export * as AzureTokenCredentials from '@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials/index.js'

The Azure token credential authentication provider of the Microsoft Graph JavaScript client (@microsoft/microsoft-graph-client 3.0.7), re-exported as-is. It connects an AzureIdentity credential to a GraphClient client.

const authProvider = new Sys.Microsoft.AzureTokenCredentials.TokenCredentialAuthenticationProvider(credential, {
scopes: ['https://graph.microsoft.com/.default'],
})

Type: module namespace of @microsoft/microsoft-graph-client/authProviders/azureTokenCredentials · Availability: Server

Note

The type declarations for this module are missing, so the code editor offers no completion or type checking for it.

export * as GraphClient from '@microsoft/microsoft-graph-client'

The Microsoft Graph JavaScript client (@microsoft/microsoft-graph-client 3.0.7), re-exported as-is. Use it for Graph requests that the simple clients do not cover.

const client = Sys.Microsoft.GraphClient.Client.initWithMiddleware({ authProvider })
const me = await client.api('/me').get()

Type: module namespace of @microsoft/microsoft-graph-client · Availability: Server

export * as OpenAi from '@azure/openai'

The @azure/openai package, version 2.0.0, re-exported as-is. In this version the package exports nothing at runtime: it only adds Azure-specific types to the openai package. To use Azure OpenAI, use Sys.Ai.SimpleAi.

Type: module namespace of @azure/openai (empty) · Availability: Server

A Graph client that authenticates as an app registration in Microsoft Entra ID with a client secret. It can do whatever the application permissions granted to the app registration allow.

const graph = new Sys.Microsoft.SimpleGraphApplicationClient({
tenantId: '00000000-0000-0000-0000-000000000000',
clientId: '11111111-1111-1111-1111-111111111111',
clientSecret: clientSecret, // for example from a configuration item
})
const salesUsers = await graph.users.get({
select: ['id', 'displayName', 'mail'],
filter: { department: 'Sales', accountEnabled: true },
orderBy: ['displayName'],
limit: 0, // all pages
})
await graph.users.item(salesUsers[0].id).sendMail({
subject: 'Monthly report',
body: { contentType: 'text', content: 'The report is ready.' },
toRecipients: [{ emailAddress: { address: 'controlling@example.com' } }],
})
constructor(connectionOptions: GraphApplicationClientConnectionOptions, options?: GraphClientOptions)

Creates a client for an app registration. The token is requested with the scope .default, so the client has all application permissions granted to the app registration.

ParameterTypeDescription
connectionOptionsGraphApplicationClientConnectionOptionsCredentials of the app registration.
optionsGraphClientOptionsOptional. Graph version and request batching.

GraphApplicationClientConnectionOptions fields

FieldTypeRequiredDescription
tenantIdstringYesID of the Microsoft Entra tenant.
clientIdstringYesApplication (client) ID of the app registration.
clientSecretstringYesClient secret of the app registration.

GraphClientOptions fields

FieldTypeRequiredDescription
version'v1.0' | 'beta' | stringNoGraph API version. Defaults to the class’s defaultVersion, which is 'v1.0'.
batchRequestsWithinMsnumberNoIf set, requests made within this many milliseconds are combined into one Graph $batch request of up to 20 requests. If not set, each request is sent on its own.

Availability: Server

defaultVersion: 'v1.0' | 'beta' | (string & {})

The Graph API version used by new clients that do not set version. Defaults to 'v1.0'.

Type: 'v1.0' | 'beta' | string · Availability: Server

get users(): SimpleGraphListClient<string, typeof UserDomainClient, User, string>

Returns a list client for /users. Its item clients are user clients (see the domain client table below).

Type: SimpleGraphListClient · Availability: Server

get groups(): SimpleGraphListClient<string, typeof GroupDomainClient, Group, "uniqueName">

Returns a list client for /groups. Groups can also be addressed by uniqueName with itemByAlternateKey().

Type: SimpleGraphListClient · Availability: Server

get drives(): SimpleGraphListClient<string, typeof DriveDomainClient, Drive, string>

Returns a list client for /drives (OneDrive and SharePoint document libraries).

Type: SimpleGraphListClient · Availability: Server

get sites(): SimpleGraphListClient<string, typeof SiteDomainClient, Site, string>

Returns a list client for /sites (SharePoint sites).

Type: SimpleGraphListClient · Availability: Server

get servicePrincipals(): SimpleGraphListClient<string, typeof ServicePrincipalDomainClient, ServicePrincipal, "appId">

Returns a list client for /servicePrincipals. Service principals can also be addressed by appId with itemByAlternateKey().

Type: SimpleGraphListClient · Availability: Server

get applications(): SimpleGraphListClient<string, typeof ApplicationDomainClient, Application, "uniqueName" | "appId">

Returns a list client for /applications (app registrations). Applications can also be addressed by appId or uniqueName with itemByAlternateKey().

Type: SimpleGraphListClient · Availability: Server

get booking(): BookingDomainClient

Returns a client for Microsoft Bookings, with the list clients businesses and currencies.

Type: BookingDomainClient · Availability: Server

A Graph client that acts on behalf of a user, with the delegated permissions the user granted when signing in through a Microsoft identity provider. It has all members of SimpleGraphApplicationClient (defaultVersion, users, groups, drives, sites, servicePrincipals, applications and booking), plus me.

const graph = new Sys.Microsoft.SimpleGraphUserClient({
userOrId: Sys.User.currentUser,
identityProviderId: 'entra', // ID of the identity provider the user signed in with
})
const files = await graph.me.drive.root.children.get({ select: ['name', 'size', 'webUrl'] })
constructor(connectionOptions: GraphUserClientConnectionOptions, options?: GraphClientOptions)

Creates a client for a user’s Microsoft account.

ParameterTypeDescription
connectionOptionsGraphUserClientConnectionOptionsEither a Lowgile user and identity provider, or an access token.
optionsGraphClientOptionsOptional. Graph version and request batching, as for SimpleGraphApplicationClient.

GraphUserClientConnectionOptions fields

Pass one of these two shapes:

FieldTypeRequiredDescription
userOrIdUser | stringYes, with identityProviderIdThe Lowgile user, or their ID. Lowgile uses the access token stored when the user signed in through the identity provider, and refreshes it if it is about to expire.
identityProviderIdstringYes, with userOrIdID of the identity provider the user signed in with.
accessTokenstringYes, with scopesA Graph access token obtained elsewhere.
scopesstring[]Yes, with accessTokenThe scopes of the access token.

The token is fetched once, when the client is created, and is not refreshed afterwards. Create a new client for long-running work. If the user has no valid token for the identity provider, the first request fails.

Availability: Server

get me(): UserDomainClient

Returns a user client for /me, the signed-in user.

Type: UserDomainClient · Availability: Server

A list client stands for a Graph collection, such as /users or /me/messages. It reads, counts and creates items, and gives item clients for single items. You get list clients from the properties of the Graph clients and of item clients; you do not create them yourself.

All requests are sent through the Graph $batch endpoint. A request that Graph answers with an error status rejects with a GraphBatchItemError, which has the HTTP status and the response body.

get(getOptions?: GetListOptions<ItemType>): Promise<ItemType[]>

Reads items of the collection.

ParameterTypeDescription
getOptionsGetListOptions<ItemType>Optional. Selection, filter, sorting and paging.

GetListOptions fields

FieldTypeRequiredDescription
select(keyof ItemType)[]NoProperties to return ($select).
expandExpandableKeys<ItemType>[] | ExpandableObject<ItemType>NoRelated objects to include ($expand). As an object, each key maps to true or to nested select, expand, filter, orderBy, skip and limit options.
filterFilter<ItemType>NoFilter condition ($filter), written as an object. See below.
orderBy(keyof ItemType)[]NoProperties to sort by ($orderby).
skipnumberNoNumber of items to skip ($skip).
limitnumberNoMaximum number of items. If omitted, only the first page that Graph returns is read. A positive number reads pages until that many items are found. 0 or a negative number reads all pages.
countbooleanNoRequests the total count ($count).
headersRecord<string, string | number>NoAdditional request headers.
additionalQueryParamsRecord<string, string | number | boolean>NoAdditional query parameters, for example $search.
verbosebooleanNoWrites the request URL to the server console.

A filter object combines conditions with and. Each key is a property name, and its value is one of:

ValueMeaning
A string, number, boolean or DateThe property equals the value.
An arrayThe property equals one of the values.
{ $eq, $ne, $gt, $ge, $lt, $le }Comparison with the value.
{ $startsWith, $endsWith, $contains }Text comparison (string properties).
{ $any, $all }A nested filter that any or all elements of a collection property must match.
{ $count }A comparison with the number of elements of a collection property.
A nested filter objectConditions on the properties of an object property.

Use $and, $or (arrays of filters) and $not to combine conditions, and $isOfType to restrict to a Graph type such as 'microsoft.graph.user'. For example, { $or: [{ department: 'Sales' }, { jobTitle: { $startsWith: 'Head' } }] }.

Returns: Promise<ItemType[]> · Availability: Server

Note

A has condition on an array property is sent with the wrong value. Use $any instead. String values that contain an apostrophe produce an invalid filter.

getAndCount(getOptions?: GetListOptions<ItemType>): Promise<[ItemType[], number]>

Reads items like get() and also returns the total number of matching items.

ParameterTypeDescription
getOptionsGetListOptions<ItemType>Optional. As for get().

Returns: Promise<[ItemType[], number]>: the items and the total count. · Availability: Server

count(countOptions: GetListCountOptions<ItemType>): Promise<number>

Returns the number of items that match a filter, without reading them.

ParameterTypeDescription
countOptionsGetListCountOptions<ItemType>The GetListOptions fields except select, expand, orderBy and skip. Pass {} to count all items.

Returns: Promise<number> · Availability: Server

create(data: ItemType): Promise<ItemType>

Creates an item in the collection.

ParameterTypeDescription
dataItemTypeThe new item, as a Graph object.

Returns: Promise<ItemType>: the created item, as returned by Graph. · Availability: Server

addReference(id: string): Promise<void>

Adds a reference to an existing object to the collection, for example a member to a group’s members.

ParameterTypeDescription
idstringThe @odata.id of the object, its full Graph URL.

Returns: Promise<void> · Availability: Server

item(id: ItemIdType): InstanceType<ItemClientClass>

Returns the item client for one item of the collection. No request is sent until you call a method on it.

ParameterTypeDescription
idItemIdTypeID of the item. For users, the user principal name also works.

Returns: the item client of the collection’s type · Availability: Server

itemByAlternateKey(alternateKey: AlternateKeyType | (string & {}), alternateId: string): InstanceType<ItemClientClass>

Returns the item client for an item addressed by an alternate key, such as an application’s appId.

ParameterTypeDescription
alternateKeyAlternateKeyType | stringName of the alternate key property.
alternateIdstringValue of the alternate key.

Returns: the item client of the collection’s type · Availability: Server

appendPathForItem(path: string): SimpleGraphItemClient<object>

Returns a generic item client for a Graph path below this collection, for resources the typed clients do not cover.

ParameterTypeDescription
pathstringPath to append, starting with /.

Returns: SimpleGraphItemClient<object> · Availability: Server

appendPathForList(path: string): SimpleGraphListClient<string, any, object, string>

Returns a generic list client for a Graph path below this collection.

ParameterTypeDescription
pathstringPath to append, starting with /.

Returns: SimpleGraphListClient<string, any, object, string> · Availability: Server

get $url(): string

Returns the Graph path of the collection, for example /users.

Type: string · Availability: Server

list(getOptions?: GetListOptions<ItemType>): Promise<ItemType[]>

Deprecated. Use get() instead. Reads items of the collection.

ParameterTypeDescription
getOptionsGetListOptions<ItemType>Optional. As for get().

Returns: Promise<ItemType[]> · Availability: Server

An item client stands for one Graph object, such as a user or a file. Each kind of object has its own item client (a domain client) that adds navigation properties and actions to the methods below. You get item clients from item(), itemByAlternateKey() or navigation properties such as me, drive or manager.

Domain clientReached throughAdds, among others
UserDomainClientusers.item(id), me, managermessages, mailFolders, mailFolder_inbox and the other well-known folders, events, calendar, calendars, drive, drives, joinedTeams, directReports, manager, photo, presence, sendMail(), listEvents(), listReminders(), setManager(), changePassword(), revokeSignInSessions()
GroupDomainClientgroups.item(id)members, members_ofTypeUser, owners, calendar, conversations, threads, drive, site, sites, memberOf, addFavorite(), removeFavorite()
DriveDomainClientdrives.item(id), driveroot, items, itemByAbsolutePath(), specialFolder_documents and other special folders, search()
DriveItemDomainClientroot, items.item(id), children.item(id)children, versions, permissions, uploadFile(), downloadFileContent(), downloadFileContentAsFormat(), replaceFileContent(), move(), copy(), copyAndWait(), createLink(), invite()
SiteDomainClientsites.item(id), sitedrive, lists, permissions, sites
ApplicationDomainClientapplications.item(id)owners(), appRoles, addPassword(), removePassword()
ServicePrincipalDomainClientservicePrincipals.item(id)owners(), byAppId()
MessageDomainClientmessages.item(id)attachments, sendDraft(), reply(), replyAll(), forward(), copyToFolder(), moveToFolder()

The code editor lists all members of each domain client.

get(getOptions?: GetItemOptions<ItemType>): Promise<ItemType>

Reads the object.

ParameterTypeDescription
getOptionsGetItemOptions<ItemType>Optional. The select, expand, headers, additionalQueryParams and verbose fields of GetListOptions.

Returns: Promise<ItemType> · Availability: Server

update(data: ItemType, options?: PatchItemOptions): Promise<ItemType>

Changes the given properties of the object (HTTP PATCH).

ParameterTypeDescription
dataItemTypeThe properties to change.
optionsPatchItemOptionsOptional. headers, verbose, and eTag: if set, the change only succeeds if the object still has this ETag.

Returns: Promise<ItemType> · Availability: Server

replace(data: ItemType, options?: PutItemOptions): Promise<ItemType>

Replaces the object (HTTP PUT).

ParameterTypeDescription
dataItemTypeThe new object.
optionsPutItemOptionsOptional. headers and verbose.

Returns: Promise<ItemType> · Availability: Server

deleteObject(options?: DeleteItemOptions): Promise<void>

Deletes the object.

ParameterTypeDescription
optionsDeleteItemOptionsOptional. headers, verbose, and eTag: if set, the object is only deleted if it still has this ETag.

Returns: Promise<void> · Availability: Server

setReference(fieldName: keyof ItemType, id: string): Promise<void>

Sets a single-valued reference of the object, such as a user’s manager.

ParameterTypeDescription
fieldNamekeyof ItemTypeName of the reference property.
idstringThe @odata.id of the referenced object, its full Graph URL.

Returns: Promise<void> · Availability: Server

deleteReference(): Promise<void>

Removes the reference this item client stands for, for example a member from a group when called on members.item(id). The referenced object itself is not deleted.

Returns: Promise<void> · Availability: Server

appendPathForItem(path: string): SimpleGraphItemClient<object>

Returns a generic item client for a Graph path below this object.

ParameterTypeDescription
pathstringPath to append, starting with /.

Returns: SimpleGraphItemClient<object> · Availability: Server

appendPathForList(path: string): SimpleGraphListClient<string, any, object, string>

Returns a generic list client for a Graph path below this object.

ParameterTypeDescription
pathstringPath to append, starting with /.

Returns: SimpleGraphListClient<string, any, object, string> · Availability: Server

get $url(): string

Returns the Graph path of the object, for example /users/1234.

Type: string · Availability: Server

export type * as GraphTypes from '@lg/backend/data/microsoft/graph-types.js'

Type-only namespace with the Graph object types from @microsoft/microsoft-graph-types 2.43.1, such as User, Group, Message, Event, Drive, DriveItem, Site, Team, Application and ServicePrincipal. Use them to type variables, for example const message: Sys.Microsoft.GraphTypes.Message = { subject: 'Hello' }.

Availability: Server