Kiota custom API client SPFx sample added

This commit is contained in:
Luis Mañez 2022-11-01 20:49:16 +01:00
parent eec02d8a80
commit 9665db503d
67 changed files with 2429 additions and 1 deletions

2
.gitignore vendored
View File

@ -52,3 +52,5 @@ samples/**/solution/
samples/**/temp/
samples/**/release/
samples/**/node_modules
samples/react-kiota-custom-api-client/TeamifiedApi/appsettings.Development.json
samples/react-kiota-custom-api-client/teamified-client/package-lock.json

View File

@ -0,0 +1,116 @@
# Using Kiota to generate a client to your AzureAd API and use it from a SPFx webpart
## Summary
This sample shows how you can generate a client for your custom API using Kiota, and how to use that client in an SPFx webpart. The sample contains a custom API that is secured by Azure AD and interacts with Microsoft Graph API to do some basic operations with the Teams endpoint (it allows to list all the Teams in the tenant, to get detailed info for a given Team, and to Provision a new Team with some preconfigured channels).
![kiota-spfx-sample](./assets/react-kiota-custom-api-client.png)
### About Kiota
Kiota is a tool created by Microsoft, that allows you to generate a client/SDK for any given API that is described using OpenAPI. It supports different languages, and provides some abstractions, so you can customise several things, like Auth providers, JSON serialisation, HTTP Request adapter, etc.
In this sample, in the folder ```/teamified-client/src/webparts/client``` is included the code generated by Kiota. We executed the following command:
```
kiota generate --openapi "my-api-swagger.yaml" --language typescript --namespace-name TeamifiedApiClient --class-name TeamifiedApiClient --output generated --log-level debug
```
## Used SharePoint Framework Version
![version](https://img.shields.io/badge/version-1.15-green.svg)
## Applies to
- [SharePoint Framework](https://aka.ms/spfx)
- [Microsoft 365 tenant](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/o365devprogram)
## Prerequisites
The API must be registered in your Azure Active Directory tenant. You can find more information on how to do it in these articles:
- https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient-enterpriseapi
- https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient
The API uses a ClientSecret to connect to MS Graph API, so create a Secret from Azure portal (this is not the recommended approach, but works for the demo. For production, I recommend you to use a certificate).
The API needs the following permissions to __Microsoft Graph API__:
| Scope | Type |
| ----------- | ----------------------- |
| Group.ReadWrite.All | Delegated |
| Directory.Read.All | Delegated |
Also, the API needs to be configured in the __Expose an API__ section, and configure a new scope named: __Teams.Manage__.
Once the API is registered in Azure AD, we must configure permissions for SPFx to access the API. This can be done in different ways. I suggest you to use the M365 CLI, with the following command:
```
m365 spo serviceprincipal grant add --resource 'Teamified_Services' --scope 'Teams.Manage'
```
## Solution
| Solution | Author(s) |
| ----------- | ------------------------------------------------------- |
| react-kiota-custom-api-client | [Luis Mañez](https://github.com/luismanez) ([MS MVP](https://mvp.microsoft.com/en-us/PublicProfile/5002617), [ClearPeople](https://www.clearpeople.com), [@luismanez](https://twitter.com/luismanez)) |
## Version history
| Version | Date | Comments |
| ------- | ---------------- | --------------- |
| 1.0 | November 1, 2022 | Initial release |
## Minimal Path to Awesome
- Clone this repository
- Edit the file __TeamifiedApi/appsettings.json__ with your Azure Active Directory API registration data (ClientId, TenantId, etc)
- Edit the file __teamified-client/src/webparts/teamsList/components/TeamsList.tsx__ and set the proper values in the following code:
```typescript
// #region ******************** UPDATE WITH YOUR TENANT DATA ********************
private readonly azureAdApplicationIdUri: string = "api://{AZURE_AD_CLIENT_ID}";
private readonly apiHost: string = "{YOUR_API}.azurewebsites.net";
// #endregion
```
- Ensure the API is up and running (you can run your API in localhost, using Visual Studio or the dotnet CLI, no need to publish it to Azure or any other hosting)
- Ensure that you are at the solution folder
- in the command-line run:
- **npm install**
- **gulp serve**
## Features
This extension illustrates the following concepts:
- using Kiota tool to generate a client for any API described by OpenAPI standard.
- using Kiota SPFx Authentication library, to provide Authentication to the Kiota client
- protecting a dotnet webapi using Azure AD and Microsoft.Identity.Web library
- calling MS Graph API from a dotnet webapi
## References
- [Kiota official documentation](https://microsoft.github.io/kiota/)
- [Kiota TypeScript library](https://github.com/microsoft/kiota-typescript)
- [Getting started with SharePoint Framework](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
- [Building for Microsoft teams](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/build-for-teams-overview)
- [Use Microsoft Graph in your solution](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/using-microsoft-graph-apis)
- [Publish SharePoint Framework applications to the Marketplace](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/publish-to-marketplace-overview)
- [Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) - Guidance, tooling, samples and open-source controls for your Microsoft 365 development
## Help
We do not support samples, but this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for community members to volunteer their time and help resolve issues.
If you're having issues building the solution, please run spfx doctor from within the solution folder to diagnose incompatibility issues with your environment.
You can try looking at issues related to this sample to see if anybody else is having the same issues.
You can also try looking at discussions related to this sample and see what the community is saying.
If you encounter any issues using this sample, create a new issue.
For questions regarding this sample, create a new question.
Finally, if you have an idea for improvement, make a suggestion.
## Disclaimer
THIS CODE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

View File

@ -0,0 +1,20 @@
using Teamified.Api.Teams.Models;
namespace Teamified.Api.Diagnostics;
public static class DiagnosticsModule
{
public static IEndpointRouteBuilder MapDiagnosticsEndpoints(this IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/ping", () => new Ping {
Id = Guid.NewGuid(),
Now = DateTime.Now.ToString()
})
.Produces<Ping>(200)
.WithName("Ping")
.WithTags("DiagnosticsModule")
.AllowAnonymous();
return endpoints;
}
}

View File

@ -0,0 +1,4 @@
global using Microsoft.AspNetCore.Authorization;
global using Microsoft.AspNetCore.Mvc;
global using Microsoft.Identity.Web;
global using System.Security.Claims;

View File

@ -0,0 +1,74 @@
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.OpenApi.Models;
using Teamified.Api.Diagnostics;
using Teamified.Api.Teams;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(
c =>
{
c.AddServer(new OpenApiServer() // Required by Kiota when creating the SDK
{
Url = "https://localhost:7295"
});
c.AddServer(new OpenApiServer()
{
Url = "https://teamifiedapi.azurewebsites.net"
});
});
builder.Services.AddMediatR(m => m.AsScoped(), typeof(Program));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(options => { builder.Configuration.Bind("AzureAd", options); })
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches(); // Advice: Use Distributed TokenCache (redis, sql...)
builder.Services.AddAuthorization(cfg => {
cfg.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
builder.Services.AddHttpContextAccessor();
const string MyAllowSpecificOrigins = "_teamifiedOpenCors";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy
.AllowAnyOrigin()
.AllowAnyHeader();
});
});
builder.Services.RegisterTeamsModule();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthentication();
app.UseAuthorization();
app.MapDiagnosticsEndpoints();
app.MapTeamsEndpoints();
app.Run();

View File

@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:26861",
"sslPort": 44374
}
},
"profiles": {
"TeamifiedApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7089;http://localhost:5115",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="10.0.1" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.25.3" />
<PackageReference Include="Microsoft.Identity.Web.TokenCache" Version="1.25.3" />
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.25.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,35 @@
using MediatR;
using Teamified.Api.Teams.Interfaces;
using Teamified.Api.Teams.Models;
namespace Teamified.Api.Teams.Commands.ProvisionTeam;
public class ProvisionTeamCommand : IRequest<string>
{
public string DisplayName { get; set; }
public string Description { get; set; }
}
public class ProvisionTeamCommandHandler : IRequestHandler<ProvisionTeamCommand, string>
{
private readonly ITeamsService _teamsService;
public ProvisionTeamCommandHandler(ITeamsService teamsService)
{
_teamsService = teamsService;
}
public async Task<string> Handle(
ProvisionTeamCommand request,
CancellationToken cancellationToken)
{
var team = new Team
{
DisplayName = request.DisplayName,
Description = request.Description
};
var newTeamLocation = await _teamsService.ProvisionTeam(team);
return newTeamLocation;
}
}

View File

@ -0,0 +1,15 @@
using MediatR;
using Teamified.Api.Teams.Queries.GetTeam;
namespace Teamified.Api.Teams.Endpoints;
public static class GetTeam
{
public static async Task<IResult> Handle(
IMediator mediator, Guid id)
{
var teams = await mediator.Send(new GetTeamQuery { GroupId = id });
return Results.Ok(teams);
}
}

View File

@ -0,0 +1,15 @@
using MediatR;
using Teamified.Api.Teams.Queries.ListTeams;
namespace Teamified.Api.Teams.Endpoints
{
public class ListTeams
{
public static async Task<IResult> Handle(IMediator mediator)
{
var teams = await mediator.Send(new ListTeamsQuery());
return Results.Ok(teams);
}
}
}

View File

@ -0,0 +1,17 @@
using MediatR;
using Teamified.Api.Teams.Commands.ProvisionTeam;
namespace Teamified.Api.Teams.Endpoints
{
public class ProvisionTeam
{
public static async Task<IResult> Handle(
IMediator mediator,
ProvisionTeamCommand command)
{
var newTeamLocation = await mediator.Send(command);
return Results.Accepted(newTeamLocation);
}
}
}

View File

@ -0,0 +1,112 @@
using Microsoft.Graph;
using Teamified.Api.Teams.Interfaces;
namespace Teamified.Api.Teams.Infrastructure;
public class TeamsService : ITeamsService
{
private readonly GraphServiceClient _graphServiceClient;
private readonly IHttpContextAccessor _context;
public TeamsService(
GraphServiceClient graphServiceClient,
IHttpContextAccessor httpContextAccessor)
{
_graphServiceClient = graphServiceClient;
_context = httpContextAccessor;
}
public async Task<Models.Team> GetTeamByGroupId(Guid groupId)
{
var group = await _graphServiceClient.Groups[groupId.ToString()]
.Request()
.Expand("members($select=id,displayName,userPrincipalName,jobTitle,mail)") // can´t expand more than 1 item (owners, members does not work)
.Select(g => new { g.Id, g.DisplayName, g.Description, g.Members })
.GetAsync();
var team = Models.Team.MapFromGraphGroup(group);
var groupOwners = await _graphServiceClient.Groups[groupId.ToString()]
.Owners
.Request()
.Select("id,displayName,userPrincipalName,jobTitle,mail")
.GetAsync();
var owners = groupOwners.CurrentPage;
team.AddOwners(owners);
var teamChannels = await _graphServiceClient.Teams[groupId.ToString()]
.Channels
.Request()
.GetAsync();
var channels = teamChannels.CurrentPage;
team.AddChannels(channels);
return team;
}
public async Task<IEnumerable<Models.Team>> ListTeams()
{
var teamsCollection = await _graphServiceClient.Groups
.Request()
.Filter("resourceProvisioningOptions/Any(x:x eq 'Team')")
.Expand("members($select=id,displayName,userPrincipalName,jobTitle,mail)") // can´t expand more than 1 item (owners, members does not work), but for this Listing endpoint is fine.
.Select(g => new { g.Id, g.DisplayName, g.Description, g.Members })
.GetAsync();
var teams = teamsCollection.CurrentPage;
var result = teams.Select(t => Models.Team.MapFromGraphGroup(t));
return result;
}
public async Task<string> ProvisionTeam(Models.Team team)
{
var currentUserId = _context.HttpContext.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
var newTeam = new Team()
{
DisplayName = team.DisplayName,
Description = team.Description,
AdditionalData = new Dictionary<string, object>()
{
{"template@odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
},
Members = new TeamMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<string>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user@odata.bind", $"https://graph.microsoft.com/v1.0/users/{currentUserId}"}
}
}
}, Channels = new TeamChannelsCollectionPage
{
new Channel
{
DisplayName = "KickOff Channel",
IsFavoriteByDefault = true,
Description = "As per company policy, place here data related with the Kickoff of the Team"
}
}
};
var result = await _graphServiceClient.Teams
.Request()
.AddResponseAsync(newTeam);
if (result.HttpHeaders.TryGetValues("Location", out var locationValues))
{
return locationValues?.First();
}
return "Something went wrong. Location not found";
}
}

View File

@ -0,0 +1,11 @@
using Teamified.Api.Teams.Models;
namespace Teamified.Api.Teams.Interfaces
{
public interface ITeamsService
{
Task<IEnumerable<Team>> ListTeams();
Task<Team> GetTeamByGroupId(Guid groupId);
Task<string> ProvisionTeam(Team team);
}
}

View File

@ -0,0 +1,25 @@
namespace Teamified.Api.Teams.Models;
public sealed class Channel
{
public string Id { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public Channel()
{
Id = "unknown";
DisplayName = "unknown";
Description = "unknown";
}
internal static Channel MapFromGraphChannel(Microsoft.Graph.Channel c)
{
return new Channel
{
Id = c.Id,
DisplayName = c.DisplayName,
Description = c.Description
};
}
}

View File

@ -0,0 +1,32 @@
using Microsoft.Graph;
namespace Teamified.Api.Teams.Models;
public sealed class IdentityPrincipal
{
public Guid Id { get; set; }
public string UserPrincipalName { get; set; }
public string Email { get; set; }
public string DisplayName { get; set; }
public string JobTitle { get; set; }
public IdentityPrincipal()
{
UserPrincipalName = "unknown";
Email = "unknown";
DisplayName = "unknown";
JobTitle = "unknown";
}
public static IdentityPrincipal MapFromDirectoryObject(DirectoryObject directoryObject)
{
return new IdentityPrincipal
{
Id = Guid.Parse(directoryObject.Id),
DisplayName = ((User)directoryObject).DisplayName,
Email = ((User)directoryObject).Mail,
JobTitle = ((User)directoryObject).JobTitle,
UserPrincipalName = ((User)directoryObject).UserPrincipalName
};
}
}

View File

@ -0,0 +1,7 @@
namespace Teamified.Api.Teams.Models;
public class Ping
{
public Guid Id { get; set; }
public string Now { get; set; }
}

View File

@ -0,0 +1,45 @@
using Microsoft.Graph;
namespace Teamified.Api.Teams.Models;
public sealed class Team
{
public string Id { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public IEnumerable<IdentityPrincipal> Owners { get; set; }
public IEnumerable<IdentityPrincipal> Members { get; set; }
public IEnumerable<Channel> Channels { get; set; }
public Team()
{
Id = "unknown";
DisplayName = "unknown";
Description = "unknown";
Owners = new List<IdentityPrincipal>();
Members = new List<IdentityPrincipal>();
Channels = new List<Channel>();
}
public static Team MapFromGraphGroup(Group graphGroup)
{
return new Team
{
Id = graphGroup.Id,
Description = graphGroup.Description,
DisplayName = graphGroup.DisplayName,
Members = graphGroup.Members != null ? graphGroup.Members.Select(m => IdentityPrincipal.MapFromDirectoryObject(m)) : new List<IdentityPrincipal>(),
Owners = graphGroup.Owners != null ? graphGroup.Owners.Select(o => IdentityPrincipal.MapFromDirectoryObject(o)) : new List<IdentityPrincipal>()
};
}
internal void AddOwners(IList<DirectoryObject> owners)
{
Owners = owners.Select(o => IdentityPrincipal.MapFromDirectoryObject(o));
}
internal void AddChannels(IList<Microsoft.Graph.Channel> channels)
{
Channels = channels.Select(c => Channel.MapFromGraphChannel(c));
}
}

View File

@ -0,0 +1,27 @@
using MediatR;
using Teamified.Api.Teams.Interfaces;
using Teamified.Api.Teams.Models;
namespace Teamified.Api.Teams.Queries.GetTeam;
public sealed class GetTeamQuery : IRequest<Team>
{
public Guid GroupId { get; set; }
}
public sealed class GetTeamQueryHandler : IRequestHandler<GetTeamQuery, Team>
{
private readonly ITeamsService _teamsService;
public GetTeamQueryHandler(ITeamsService teamsService)
{
_teamsService = teamsService;
}
public async Task<Team> Handle(
GetTeamQuery request,
CancellationToken cancellationToken)
{
return await _teamsService.GetTeamByGroupId(request.GroupId);
}
}

View File

@ -0,0 +1,27 @@
using MediatR;
using Teamified.Api.Teams.Interfaces;
using Teamified.Api.Teams.Models;
namespace Teamified.Api.Teams.Queries.ListTeams;
public class ListTeamsQuery : IRequest<IEnumerable<Team>>
{
}
public class ListTeamsQueryHandler : IRequestHandler<ListTeamsQuery, IEnumerable<Team>>
{
private readonly ITeamsService _teamsService;
public ListTeamsQueryHandler(ITeamsService teamsService)
{
_teamsService = teamsService;
}
public async Task<IEnumerable<Team>> Handle(
ListTeamsQuery request,
CancellationToken cancellationToken)
{
return await _teamsService.ListTeams();
}
}

View File

@ -0,0 +1,37 @@
using Teamified.Api.Teams.Endpoints;
using Teamified.Api.Teams.Infrastructure;
using Teamified.Api.Teams.Interfaces;
using Teamified.Api.Teams.Models;
namespace Teamified.Api.Teams
{
public static class TeamsModule
{
public static IServiceCollection RegisterTeamsModule(this IServiceCollection services)
{
services.AddScoped<ITeamsService, TeamsService>();
return services;
}
public static IEndpointRouteBuilder MapTeamsEndpoints(this IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/teams", ListTeams.Handle)
.Produces<IEnumerable<Team>>(200)
.WithName("ListTeams")
.WithTags("TeamsModule");
endpoints.MapGet("/teams/{id:guid}", GetTeam.Handle)
.Produces<Team>(200)
.WithName("GetTeam")
.WithTags("TeamsModule");
endpoints.MapPost("/teams", ProvisionTeam.Handle)
.Produces<string>(202)
.WithName("ProvisionTeam")
.WithTags("TeamsModule");
return endpoints;
}
}
}

View File

@ -0,0 +1,19 @@
{
//"AzureAd": {
// "Instance": "https://login.microsoftonline.com/",
// "ClientId": "",
// "TenantId": "",
// "ClientSecret": ""
//},
//"MicrosoftGraph": {
// "BaseUrl": "https://graph.microsoft.com/v1.0",
// "Scopes": "https://graph.microsoft.com/.default"
//},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

View File

@ -0,0 +1,378 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 1,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
'@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
1,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'error',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {
'no-new': 0,
'class-name': 0,
'export-name': 0,
forin: 0,
'label-position': 0,
'member-access': 2,
'no-arg': 0,
'no-console': 0,
'no-construct': 0,
'no-duplicate-variable': 2,
'no-eval': 0,
'no-function-expression': 2,
'no-internal-module': 2,
'no-shadowed-variable': 2,
'no-switch-case-fall-through': 2,
'no-unnecessary-semicolons': 2,
'no-unused-expression': 2,
'no-with-statement': 2,
semicolon: 2,
'trailing-comma': 0,
typedef: 0,
'typedef-whitespace': 0,
'use-named-parameter': 2,
'variable-name': 0,
whitespace: 0
}
}
]
};

View File

@ -0,0 +1,34 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
.heft
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,16 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"version": "1.15.2",
"libraryName": "teamified-client",
"libraryId": "8635e38d-a794-47a5-8ee4-447fece15941",
"environment": "spo",
"packageManager": "npm",
"solutionName": "teamified-client",
"solutionShortDescription": "teamified-client description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,73 @@
# teamified-client
## Summary
Short summary on functionality and used technologies.
[picture of the solution in action, if possible]
## Used SharePoint Framework Version
![version](https://img.shields.io/badge/version-1.13-green.svg)
## Applies to
- [SharePoint Framework](https://aka.ms/spfx)
- [Microsoft 365 tenant](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/o365devprogram)
## Prerequisites
> Any special pre-requisites?
## Solution
| Solution | Author(s) |
| ----------- | ------------------------------------------------------- |
| folder name | Author details (name, company, twitter alias with link) |
## Version history
| Version | Date | Comments |
| ------- | ---------------- | --------------- |
| 1.1 | March 10, 2021 | Update comment |
| 1.0 | January 29, 2021 | Initial release |
## Disclaimer
**THIS CODE IS PROVIDED _AS IS_ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
---
## Minimal Path to Awesome
- Clone this repository
- Ensure that you are at the solution folder
- in the command-line run:
- **npm install**
- **gulp serve**
> Include any additional steps as needed.
## Features
Description of the extension that expands upon high-level summary above.
This extension illustrates the following concepts:
- topic 1
- topic 2
- topic 3
> Notice that better pictures and documentation will increase the sample usage and the value you are providing for others. Thanks for your submissions advance.
> Share your web part with others through Microsoft 365 Patterns and Practices program to get visibility and exposure. More details on the community, open-source projects and other activities from http://aka.ms/m365pnp.
## References
- [Getting started with SharePoint Framework](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
- [Building for Microsoft teams](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/build-for-teams-overview)
- [Use Microsoft Graph in your solution](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/using-microsoft-graph-apis)
- [Publish SharePoint Framework applications to the Marketplace](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/publish-to-marketplace-overview)
- [Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) - Guidance, tooling, samples and open-source controls for your Microsoft 365 development

View File

@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"teams-list-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/teamsList/TeamsListWebPart.js",
"manifest": "./src/webparts/teamsList/TeamsListWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"TeamsListWebPartStrings": "lib/webparts/teamsList/loc/{locale}.js"
}
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "teamified-client",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,40 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "teamified-client-client-side-solution",
"id": "8635e38d-a794-47a5-8ee4-447fece15941",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.15.2"
},
"metadata": {
"shortDescription": {
"default": "teamified-client description"
},
"longDescription": {
"default": "teamified-client description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "teamified-client Feature",
"description": "The feature that activates elements of the teamified-client solution.",
"id": "5940d3fd-d3e8-44be-a153-d25e04db2c11",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/teamified-client.sppkg"
}
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://enter-your-SharePoint-site/_layouts/workbench.aspx"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,16 @@
'use strict';
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));

View File

@ -0,0 +1,43 @@
{
"name": "teamified-client",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@fluentui/react": "^8.99.2",
"@microsoft/kiota-abstractions": "^1.0.0-preview.6",
"@microsoft/kiota-authentication-spfx": "^1.0.0-preview.1",
"@microsoft/kiota-http-fetchlibrary": "^1.0.0-preview.8",
"@microsoft/kiota-serialization-json": "^1.0.0-preview.8",
"@microsoft/kiota-serialization-text": "^1.0.0-preview.7",
"@microsoft/sp-core-library": "1.15.2",
"@microsoft/sp-lodash-subset": "1.15.2",
"@microsoft/sp-office-ui-fabric-core": "1.15.2",
"@microsoft/sp-property-pane": "1.15.2",
"@microsoft/sp-webpart-base": "1.15.2",
"office-ui-fabric-react": "7.185.7",
"react": "16.13.1",
"react-dom": "16.13.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/rush-stack-compiler-4.5": "0.2.2",
"@rushstack/eslint-config": "2.5.1",
"@microsoft/eslint-plugin-spfx": "1.15.2",
"@microsoft/eslint-config-spfx": "1.15.2",
"@microsoft/sp-build-web": "1.15.2",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"gulp": "4.0.2",
"typescript": "4.5.5",
"@types/react": "16.9.51",
"@types/react-dom": "16.9.8",
"eslint-plugin-react-hooks": "4.3.0",
"@microsoft/sp-module-interfaces": "1.15.2"
}
}

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,28 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "a4533e12-f41c-448b-a1c8-2cb0ce6ad3bc",
"alias": "TeamsListWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Advanced
"group": { "default": "Advanced" },
"title": { "default": "TeamsList" },
"description": { "default": "TeamsList description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "TeamsList"
}
}]
}

View File

@ -0,0 +1,101 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import * as strings from 'TeamsListWebPartStrings';
import TeamsList from './components/TeamsList';
import { ITeamsListProps } from './components/ITeamsListProps';
export interface ITeamsListWebPartProps {
description: string;
}
export default class TeamsListWebPart extends BaseClientSideWebPart<ITeamsListWebPartProps> {
private _isDarkTheme: boolean = false;
private _environmentMessage: string = '';
public render(): void {
const element: React.ReactElement<ITeamsListProps> = React.createElement(
TeamsList,
{
description: this.properties.description,
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
userDisplayName: this.context.pageContext.user.displayName,
aadTokenProviderFactory: this.context.aadTokenProviderFactory
}
);
ReactDom.render(element, this.domElement);
}
protected onInit(): Promise<void> {
this._environmentMessage = this._getEnvironmentMessage();
return super.onInit();
}
private _getEnvironmentMessage(): string {
if (!!this.context.sdks.microsoftTeams) { // running in Teams
return this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentTeams : strings.AppTeamsTabEnvironment;
}
return this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentSharePoint : strings.AppSharePointEnvironment;
}
protected onThemeChanged(currentTheme: IReadonlyTheme | undefined): void {
if (!currentTheme) {
return;
}
this._isDarkTheme = !!currentTheme.isInverted;
const {
semanticColors
} = currentTheme;
if (semanticColors) {
this.domElement.style.setProperty('--bodyText', semanticColors.bodyText || null);
this.domElement.style.setProperty('--link', semanticColors.link || null);
this.domElement.style.setProperty('--linkHovered', semanticColors.linkHovered || null);
}
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@ -0,0 +1,73 @@
import {Parsable, ParseNode, SerializationWriter} from '@microsoft/kiota-abstractions';
export class Channel implements Parsable {
/** The description property */
private _description?: string | undefined;
/** The displayName property */
private _displayName?: string | undefined;
/** The id property */
private _id?: string | undefined;
/**
* Gets the description property value. The description property
* @returns a string
*/
public get description() {
return this._description;
};
/**
* Sets the description property value. The description property
* @param value Value to set for the description property.
*/
public set description(value: string | undefined) {
this._description = value;
};
/**
* Gets the displayName property value. The displayName property
* @returns a string
*/
public get displayName() {
return this._displayName;
};
/**
* Sets the displayName property value. The displayName property
* @param value Value to set for the displayName property.
*/
public set displayName(value: string | undefined) {
this._displayName = value;
};
/**
* The deserialization information for the current model
* @returns a Record<string, (node: ParseNode) => void>
*/
public getFieldDeserializers() : Record<string, (node: ParseNode) => void> {
return {
"description": n => { this.description = n.getStringValue(); },
"displayName": n => { this.displayName = n.getStringValue(); },
"id": n => { this.id = n.getStringValue(); },
};
};
/**
* Gets the id property value. The id property
* @returns a string
*/
public get id() {
return this._id;
};
/**
* Sets the id property value. The id property
* @param value Value to set for the id property.
*/
public set id(value: string | undefined) {
this._id = value;
};
/**
* Serializes information the current object
* @param writer Serialization writer to use to serialize this model
*/
public serialize(writer: SerializationWriter) : void {
if(!writer) throw new Error("writer cannot be undefined");
writer.writeStringValue("description", this.description);
writer.writeStringValue("displayName", this.displayName);
writer.writeStringValue("id", this.id);
};
}

View File

@ -0,0 +1,7 @@
import {Channel} from './index';
import {ParseNode} from '@microsoft/kiota-abstractions';
export function createChannelFromDiscriminatorValue(parseNode: ParseNode | undefined) : Channel {
if(!parseNode) throw new Error("parseNode cannot be undefined");
return new Channel();
}

View File

@ -0,0 +1,7 @@
import {IdentityPrincipal} from './index';
import {ParseNode} from '@microsoft/kiota-abstractions';
export function createIdentityPrincipalFromDiscriminatorValue(parseNode: ParseNode | undefined) : IdentityPrincipal {
if(!parseNode) throw new Error("parseNode cannot be undefined");
return new IdentityPrincipal();
}

View File

@ -0,0 +1,7 @@
import {Ping} from './index';
import {ParseNode} from '@microsoft/kiota-abstractions';
export function createPingFromDiscriminatorValue(parseNode: ParseNode | undefined) : Ping {
if(!parseNode) throw new Error("parseNode cannot be undefined");
return new Ping();
}

View File

@ -0,0 +1,7 @@
import {ProvisionTeamCommand} from './index';
import {ParseNode} from '@microsoft/kiota-abstractions';
export function createProvisionTeamCommandFromDiscriminatorValue(parseNode: ParseNode | undefined) : ProvisionTeamCommand {
if(!parseNode) throw new Error("parseNode cannot be undefined");
return new ProvisionTeamCommand();
}

View File

@ -0,0 +1,7 @@
import {Team} from './index';
import {ParseNode} from '@microsoft/kiota-abstractions';
export function createTeamFromDiscriminatorValue(parseNode: ParseNode | undefined) : Team {
if(!parseNode) throw new Error("parseNode cannot be undefined");
return new Team();
}

View File

@ -0,0 +1,109 @@
import {Parsable, ParseNode, SerializationWriter} from '@microsoft/kiota-abstractions';
export class IdentityPrincipal implements Parsable {
/** The displayName property */
private _displayName?: string | undefined;
/** The email property */
private _email?: string | undefined;
/** The id property */
private _id?: string | undefined;
/** The jobTitle property */
private _jobTitle?: string | undefined;
/** The userPrincipalName property */
private _userPrincipalName?: string | undefined;
/**
* Gets the displayName property value. The displayName property
* @returns a string
*/
public get displayName() {
return this._displayName;
};
/**
* Sets the displayName property value. The displayName property
* @param value Value to set for the displayName property.
*/
public set displayName(value: string | undefined) {
this._displayName = value;
};
/**
* Gets the email property value. The email property
* @returns a string
*/
public get email() {
return this._email;
};
/**
* Sets the email property value. The email property
* @param value Value to set for the email property.
*/
public set email(value: string | undefined) {
this._email = value;
};
/**
* The deserialization information for the current model
* @returns a Record<string, (node: ParseNode) => void>
*/
public getFieldDeserializers() : Record<string, (node: ParseNode) => void> {
return {
"displayName": n => { this.displayName = n.getStringValue(); },
"email": n => { this.email = n.getStringValue(); },
"id": n => { this.id = n.getStringValue(); },
"jobTitle": n => { this.jobTitle = n.getStringValue(); },
"userPrincipalName": n => { this.userPrincipalName = n.getStringValue(); },
};
};
/**
* Gets the id property value. The id property
* @returns a string
*/
public get id() {
return this._id;
};
/**
* Sets the id property value. The id property
* @param value Value to set for the id property.
*/
public set id(value: string | undefined) {
this._id = value;
};
/**
* Gets the jobTitle property value. The jobTitle property
* @returns a string
*/
public get jobTitle() {
return this._jobTitle;
};
/**
* Sets the jobTitle property value. The jobTitle property
* @param value Value to set for the jobTitle property.
*/
public set jobTitle(value: string | undefined) {
this._jobTitle = value;
};
/**
* Serializes information the current object
* @param writer Serialization writer to use to serialize this model
*/
public serialize(writer: SerializationWriter) : void {
if(!writer) throw new Error("writer cannot be undefined");
writer.writeStringValue("displayName", this.displayName);
writer.writeStringValue("email", this.email);
writer.writeStringValue("id", this.id);
writer.writeStringValue("jobTitle", this.jobTitle);
writer.writeStringValue("userPrincipalName", this.userPrincipalName);
};
/**
* Gets the userPrincipalName property value. The userPrincipalName property
* @returns a string
*/
public get userPrincipalName() {
return this._userPrincipalName;
};
/**
* Sets the userPrincipalName property value. The userPrincipalName property
* @param value Value to set for the userPrincipalName property.
*/
public set userPrincipalName(value: string | undefined) {
this._userPrincipalName = value;
};
}

View File

@ -0,0 +1,5 @@
export * from './team'
export * from './ping'
export * from './identityPrincipal'
export * from './provisionTeamCommand'
export * from './channel'

View File

@ -0,0 +1,55 @@
import {Parsable, ParseNode, SerializationWriter} from '@microsoft/kiota-abstractions';
export class Ping implements Parsable {
/** The id property */
private _id?: string | undefined;
/** The now property */
private _now?: string | undefined;
/**
* The deserialization information for the current model
* @returns a Record<string, (node: ParseNode) => void>
*/
public getFieldDeserializers() : Record<string, (node: ParseNode) => void> {
return {
"id": n => { this.id = n.getStringValue(); },
"now": n => { this.now = n.getStringValue(); },
};
};
/**
* Gets the id property value. The id property
* @returns a string
*/
public get id() {
return this._id;
};
/**
* Sets the id property value. The id property
* @param value Value to set for the id property.
*/
public set id(value: string | undefined) {
this._id = value;
};
/**
* Gets the now property value. The now property
* @returns a string
*/
public get now() {
return this._now;
};
/**
* Sets the now property value. The now property
* @param value Value to set for the now property.
*/
public set now(value: string | undefined) {
this._now = value;
};
/**
* Serializes information the current object
* @param writer Serialization writer to use to serialize this model
*/
public serialize(writer: SerializationWriter) : void {
if(!writer) throw new Error("writer cannot be undefined");
writer.writeStringValue("id", this.id);
writer.writeStringValue("now", this.now);
};
}

View File

@ -0,0 +1,55 @@
import {Parsable, ParseNode, SerializationWriter} from '@microsoft/kiota-abstractions';
export class ProvisionTeamCommand implements Parsable {
/** The description property */
private _description?: string | undefined;
/** The displayName property */
private _displayName?: string | undefined;
/**
* Gets the description property value. The description property
* @returns a string
*/
public get description() {
return this._description;
};
/**
* Sets the description property value. The description property
* @param value Value to set for the description property.
*/
public set description(value: string | undefined) {
this._description = value;
};
/**
* Gets the displayName property value. The displayName property
* @returns a string
*/
public get displayName() {
return this._displayName;
};
/**
* Sets the displayName property value. The displayName property
* @param value Value to set for the displayName property.
*/
public set displayName(value: string | undefined) {
this._displayName = value;
};
/**
* The deserialization information for the current model
* @returns a Record<string, (node: ParseNode) => void>
*/
public getFieldDeserializers() : Record<string, (node: ParseNode) => void> {
return {
"description": n => { this.description = n.getStringValue(); },
"displayName": n => { this.displayName = n.getStringValue(); },
};
};
/**
* Serializes information the current object
* @param writer Serialization writer to use to serialize this model
*/
public serialize(writer: SerializationWriter) : void {
if(!writer) throw new Error("writer cannot be undefined");
writer.writeStringValue("description", this.description);
writer.writeStringValue("displayName", this.displayName);
};
}

View File

@ -0,0 +1,130 @@
import {createChannelFromDiscriminatorValue} from './createChannelFromDiscriminatorValue';
import {createIdentityPrincipalFromDiscriminatorValue} from './createIdentityPrincipalFromDiscriminatorValue';
import {Channel, IdentityPrincipal} from './index';
import {Parsable, ParseNode, SerializationWriter} from '@microsoft/kiota-abstractions';
export class Team implements Parsable {
/** The channels property */
private _channels?: Channel[] | undefined;
/** The description property */
private _description?: string | undefined;
/** The displayName property */
private _displayName?: string | undefined;
/** The id property */
private _id?: string | undefined;
/** The members property */
private _members?: IdentityPrincipal[] | undefined;
/** The owners property */
private _owners?: IdentityPrincipal[] | undefined;
/**
* Gets the channels property value. The channels property
* @returns a Channel
*/
public get channels() {
return this._channels;
};
/**
* Sets the channels property value. The channels property
* @param value Value to set for the channels property.
*/
public set channels(value: Channel[] | undefined) {
this._channels = value;
};
/**
* Gets the description property value. The description property
* @returns a string
*/
public get description() {
return this._description;
};
/**
* Sets the description property value. The description property
* @param value Value to set for the description property.
*/
public set description(value: string | undefined) {
this._description = value;
};
/**
* Gets the displayName property value. The displayName property
* @returns a string
*/
public get displayName() {
return this._displayName;
};
/**
* Sets the displayName property value. The displayName property
* @param value Value to set for the displayName property.
*/
public set displayName(value: string | undefined) {
this._displayName = value;
};
/**
* The deserialization information for the current model
* @returns a Record<string, (node: ParseNode) => void>
*/
public getFieldDeserializers() : Record<string, (node: ParseNode) => void> {
return {
"channels": n => { this.channels = n.getCollectionOfObjectValues<Channel>(createChannelFromDiscriminatorValue); },
"description": n => { this.description = n.getStringValue(); },
"displayName": n => { this.displayName = n.getStringValue(); },
"id": n => { this.id = n.getStringValue(); },
"members": n => { this.members = n.getCollectionOfObjectValues<IdentityPrincipal>(createIdentityPrincipalFromDiscriminatorValue); },
"owners": n => { this.owners = n.getCollectionOfObjectValues<IdentityPrincipal>(createIdentityPrincipalFromDiscriminatorValue); },
};
};
/**
* Gets the id property value. The id property
* @returns a string
*/
public get id() {
return this._id;
};
/**
* Sets the id property value. The id property
* @param value Value to set for the id property.
*/
public set id(value: string | undefined) {
this._id = value;
};
/**
* Gets the members property value. The members property
* @returns a IdentityPrincipal
*/
public get members() {
return this._members;
};
/**
* Sets the members property value. The members property
* @param value Value to set for the members property.
*/
public set members(value: IdentityPrincipal[] | undefined) {
this._members = value;
};
/**
* Gets the owners property value. The owners property
* @returns a IdentityPrincipal
*/
public get owners() {
return this._owners;
};
/**
* Sets the owners property value. The owners property
* @param value Value to set for the owners property.
*/
public set owners(value: IdentityPrincipal[] | undefined) {
this._owners = value;
};
/**
* Serializes information the current object
* @param writer Serialization writer to use to serialize this model
*/
public serialize(writer: SerializationWriter) : void {
if(!writer) throw new Error("writer cannot be undefined");
writer.writeCollectionOfObjectValues<Channel>("channels", this.channels);
writer.writeStringValue("description", this.description);
writer.writeStringValue("displayName", this.displayName);
writer.writeStringValue("id", this.id);
writer.writeCollectionOfObjectValues<IdentityPrincipal>("members", this.members);
writer.writeCollectionOfObjectValues<IdentityPrincipal>("owners", this.owners);
};
}

View File

@ -0,0 +1,45 @@
import {Ping} from '../models/';
import {createPingFromDiscriminatorValue} from '../models/createPingFromDiscriminatorValue';
import {PingRequestBuilderGetRequestConfiguration} from './pingRequestBuilderGetRequestConfiguration';
import {getPathParameters, HttpMethod, Parsable, ParsableFactory, RequestAdapter, RequestInformation, RequestOption, ResponseHandler} from '@microsoft/kiota-abstractions';
/** Builds and executes requests for operations under /ping */
export class PingRequestBuilder {
/** Path parameters for the request */
private readonly pathParameters: Record<string, unknown>;
/** The request adapter to use to execute the requests. */
private readonly requestAdapter: RequestAdapter;
/** Url template to use to build the URL for the current request builder */
private readonly urlTemplate: string;
/**
* Instantiates a new PingRequestBuilder and sets the default values.
* @param pathParameters The raw url or the Url template parameters for the request.
* @param requestAdapter The request adapter to use to execute the requests.
*/
public constructor(pathParameters: Record<string, unknown> | string | undefined, requestAdapter: RequestAdapter) {
if(!pathParameters) throw new Error("pathParameters cannot be undefined");
if(!requestAdapter) throw new Error("requestAdapter cannot be undefined");
this.urlTemplate = "{+baseurl}/ping";
const urlTplParams = getPathParameters(pathParameters);
this.pathParameters = urlTplParams;
this.requestAdapter = requestAdapter;
};
public createGetRequestInformation(requestConfiguration?: PingRequestBuilderGetRequestConfiguration | undefined) : RequestInformation {
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.GET;
requestInfo.headers["Accept"] = "application/json";
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.addRequestOptions(requestConfiguration.options);
}
return requestInfo;
};
public get(requestConfiguration?: PingRequestBuilderGetRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<Ping | undefined> {
const requestInfo = this.createGetRequestInformation(
requestConfiguration
);
return this.requestAdapter?.sendAsync<Ping>(requestInfo, createPingFromDiscriminatorValue, responseHandler, undefined) ?? Promise.reject(new Error('http core is null'));
};
}

View File

@ -0,0 +1,9 @@
import {RequestOption} from '@microsoft/kiota-abstractions';
/** Configuration for the request such as headers, query parameters, and middleware options. */
export class PingRequestBuilderGetRequestConfiguration {
/** Request headers */
public headers?: Record<string, string> | undefined;
/** Request options */
public options?: RequestOption[] | undefined;
}

View File

@ -0,0 +1,52 @@
import {PingRequestBuilder} from './ping/pingRequestBuilder';
import {TeamsItemRequestBuilder} from './teams/item/teamsItemRequestBuilder';
import {TeamsRequestBuilder} from './teams/teamsRequestBuilder';
import {enableBackingStoreForSerializationWriterFactory, getPathParameters, ParseNodeFactoryRegistry, registerDefaultDeserializer, registerDefaultSerializer, RequestAdapter, SerializationWriterFactoryRegistry} from '@microsoft/kiota-abstractions';
import {JsonParseNodeFactory, JsonSerializationWriterFactory} from '@microsoft/kiota-serialization-json';
import {TextParseNodeFactory, TextSerializationWriterFactory} from '@microsoft/kiota-serialization-text';
/** The main entry point of the SDK, exposes the configuration and the fluent API. */
export class TeamifiedApiClient {
/** Path parameters for the request */
private readonly pathParameters: Record<string, unknown>;
/** The ping property */
public get ping(): PingRequestBuilder {
return new PingRequestBuilder(this.pathParameters, this.requestAdapter);
}
/** The request adapter to use to execute the requests. */
private readonly requestAdapter: RequestAdapter;
/** The teams property */
public get teams(): TeamsRequestBuilder {
return new TeamsRequestBuilder(this.pathParameters, this.requestAdapter);
}
/** Url template to use to build the URL for the current request builder */
private readonly urlTemplate: string;
/**
* Instantiates a new TeamifiedApiClient and sets the default values.
* @param requestAdapter The request adapter to use to execute the requests.
*/
public constructor(requestAdapter: RequestAdapter) {
if(!requestAdapter) throw new Error("requestAdapter cannot be undefined");
this.pathParameters = {};
this.urlTemplate = "{+baseurl}";
this.requestAdapter = requestAdapter;
registerDefaultSerializer(JsonSerializationWriterFactory);
registerDefaultSerializer(TextSerializationWriterFactory);
registerDefaultDeserializer(JsonParseNodeFactory);
registerDefaultDeserializer(TextParseNodeFactory);
if (requestAdapter.baseUrl === undefined || requestAdapter.baseUrl === "") {
requestAdapter.baseUrl = "https://localhost:7295";
}
};
/**
* Gets an item from the Teamified.Sdk.teams.item collection
* @param id Unique identifier of the item
* @returns a TeamsItemRequestBuilder
*/
public teamsById(id: string) : TeamsItemRequestBuilder {
if(!id) throw new Error("id cannot be undefined");
const urlTplParams = getPathParameters(this.pathParameters);
urlTplParams["id"] = id
return new TeamsItemRequestBuilder(urlTplParams, this.requestAdapter);
};
}

View File

@ -0,0 +1,45 @@
import {Team} from '../../models/';
import {createTeamFromDiscriminatorValue} from '../../models/createTeamFromDiscriminatorValue';
import {TeamsItemRequestBuilderGetRequestConfiguration} from './teamsItemRequestBuilderGetRequestConfiguration';
import {getPathParameters, HttpMethod, Parsable, ParsableFactory, RequestAdapter, RequestInformation, RequestOption, ResponseHandler} from '@microsoft/kiota-abstractions';
/** Builds and executes requests for operations under /teams/{id} */
export class TeamsItemRequestBuilder {
/** Path parameters for the request */
private readonly pathParameters: Record<string, unknown>;
/** The request adapter to use to execute the requests. */
private readonly requestAdapter: RequestAdapter;
/** Url template to use to build the URL for the current request builder */
private readonly urlTemplate: string;
/**
* Instantiates a new TeamsItemRequestBuilder and sets the default values.
* @param pathParameters The raw url or the Url template parameters for the request.
* @param requestAdapter The request adapter to use to execute the requests.
*/
public constructor(pathParameters: Record<string, unknown> | string | undefined, requestAdapter: RequestAdapter) {
if(!pathParameters) throw new Error("pathParameters cannot be undefined");
if(!requestAdapter) throw new Error("requestAdapter cannot be undefined");
this.urlTemplate = "{+baseurl}/teams/{id}";
const urlTplParams = getPathParameters(pathParameters);
this.pathParameters = urlTplParams;
this.requestAdapter = requestAdapter;
};
public createGetRequestInformation(requestConfiguration?: TeamsItemRequestBuilderGetRequestConfiguration | undefined) : RequestInformation {
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.GET;
requestInfo.headers["Accept"] = "application/json";
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.addRequestOptions(requestConfiguration.options);
}
return requestInfo;
};
public get(requestConfiguration?: TeamsItemRequestBuilderGetRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<Team | undefined> {
const requestInfo = this.createGetRequestInformation(
requestConfiguration
);
return this.requestAdapter?.sendAsync<Team>(requestInfo, createTeamFromDiscriminatorValue, responseHandler, undefined) ?? Promise.reject(new Error('http core is null'));
};
}

View File

@ -0,0 +1,9 @@
import {RequestOption} from '@microsoft/kiota-abstractions';
/** Configuration for the request such as headers, query parameters, and middleware options. */
export class TeamsItemRequestBuilderGetRequestConfiguration {
/** Request headers */
public headers?: Record<string, string> | undefined;
/** Request options */
public options?: RequestOption[] | undefined;
}

View File

@ -0,0 +1,67 @@
import {ProvisionTeamCommand, Team} from '../models/';
import {createTeamFromDiscriminatorValue} from '../models/createTeamFromDiscriminatorValue';
import {TeamsRequestBuilderGetRequestConfiguration} from './teamsRequestBuilderGetRequestConfiguration';
import {TeamsRequestBuilderPostRequestConfiguration} from './teamsRequestBuilderPostRequestConfiguration';
import {getPathParameters, HttpMethod, Parsable, ParsableFactory, RequestAdapter, RequestInformation, RequestOption, ResponseHandler} from '@microsoft/kiota-abstractions';
/** Builds and executes requests for operations under /teams */
export class TeamsRequestBuilder {
/** Path parameters for the request */
private readonly pathParameters: Record<string, unknown>;
/** The request adapter to use to execute the requests. */
private readonly requestAdapter: RequestAdapter;
/** Url template to use to build the URL for the current request builder */
private readonly urlTemplate: string;
/**
* Instantiates a new TeamsRequestBuilder and sets the default values.
* @param pathParameters The raw url or the Url template parameters for the request.
* @param requestAdapter The request adapter to use to execute the requests.
*/
public constructor(pathParameters: Record<string, unknown> | string | undefined, requestAdapter: RequestAdapter) {
if(!pathParameters) throw new Error("pathParameters cannot be undefined");
if(!requestAdapter) throw new Error("requestAdapter cannot be undefined");
this.urlTemplate = "{+baseurl}/teams";
const urlTplParams = getPathParameters(pathParameters);
this.pathParameters = urlTplParams;
this.requestAdapter = requestAdapter;
};
public createGetRequestInformation(requestConfiguration?: TeamsRequestBuilderGetRequestConfiguration | undefined) : RequestInformation {
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.GET;
requestInfo.headers["Accept"] = "application/json";
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.addRequestOptions(requestConfiguration.options);
}
return requestInfo;
};
public createPostRequestInformation(body: ProvisionTeamCommand | undefined, requestConfiguration?: TeamsRequestBuilderPostRequestConfiguration | undefined) : RequestInformation {
if(!body) throw new Error("body cannot be undefined");
const requestInfo = new RequestInformation();
requestInfo.urlTemplate = this.urlTemplate;
requestInfo.pathParameters = this.pathParameters;
requestInfo.httpMethod = HttpMethod.POST;
requestInfo.headers["Accept"] = "application/json";
if (requestConfiguration) {
requestInfo.addRequestHeaders(requestConfiguration.headers);
requestInfo.addRequestOptions(requestConfiguration.options);
}
requestInfo.setContentFromParsable(this.requestAdapter, "application/json", body);
return requestInfo;
};
public get(requestConfiguration?: TeamsRequestBuilderGetRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<Team[] | undefined> {
const requestInfo = this.createGetRequestInformation(
requestConfiguration
);
return this.requestAdapter?.sendCollectionAsync<Team>(requestInfo, createTeamFromDiscriminatorValue, responseHandler, undefined) ?? Promise.reject(new Error('http core is null'));
};
public post(body: ProvisionTeamCommand | undefined, requestConfiguration?: TeamsRequestBuilderPostRequestConfiguration | undefined, responseHandler?: ResponseHandler | undefined) : Promise<string | undefined> {
if(!body) throw new Error("body cannot be undefined");
const requestInfo = this.createPostRequestInformation(
body, requestConfiguration
);
return this.requestAdapter?.sendPrimitiveAsync<string>(requestInfo, "string", responseHandler, undefined) ?? Promise.reject(new Error('http core is null'));
};
}

View File

@ -0,0 +1,9 @@
import {RequestOption} from '@microsoft/kiota-abstractions';
/** Configuration for the request such as headers, query parameters, and middleware options. */
export class TeamsRequestBuilderGetRequestConfiguration {
/** Request headers */
public headers?: Record<string, string> | undefined;
/** Request options */
public options?: RequestOption[] | undefined;
}

View File

@ -0,0 +1,9 @@
import {RequestOption} from '@microsoft/kiota-abstractions';
/** Configuration for the request such as headers, query parameters, and middleware options. */
export class TeamsRequestBuilderPostRequestConfiguration {
/** Request headers */
public headers?: Record<string, string> | undefined;
/** Request options */
public options?: RequestOption[] | undefined;
}

View File

@ -0,0 +1,10 @@
import { AadTokenProviderFactory } from '@microsoft/sp-http';
export interface ITeamsListProps {
description: string;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
userDisplayName: string;
aadTokenProviderFactory: AadTokenProviderFactory;
}

View File

@ -0,0 +1,6 @@
import { Team } from '../client/models';
export interface ITeamsListState {
teams: Team[];
}

View File

@ -0,0 +1,50 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.teamsList {
overflow: hidden;
padding: 1em;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}
ul.nobullets {
list-style-type: none; /* Remove bullets */
padding: 5px; /* Remove padding */
margin: 0; /* Remove margins */
}
.welcome {
text-align: center;
}
.welcomeImage {
max-width: 420px;
}
.facepile {
padding-left: 15px;
}
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr;
padding: 5px;
row-gap: 1em;
}
.links {
a {
text-decoration: none;
color: "[theme:link, default:#03787c]";
color: var(--link); // note: CSS Custom Properties support is limited to modern browsers only
&:hover {
text-decoration: underline;
color: "[theme:linkHovered, default: #014446]";
color: var(--linkHovered); // note: CSS Custom Properties support is limited to modern browsers only
}
}
}

View File

@ -0,0 +1,124 @@
import * as React from 'react';
import styles from './TeamsList.module.scss';
import { ITeamsListProps } from './ITeamsListProps';
import { ITeamsListState } from "./ITeamsListState";
import { escape } from '@microsoft/sp-lodash-subset';
import { AadTokenProvider } from '@microsoft/sp-http';
import { FetchRequestAdapter } from '@microsoft/kiota-http-fetchlibrary';
import { TeamifiedApiClient } from '../client/teamifiedApiClient';
import { AzureAdSpfxAuthenticationProvider } from '@microsoft/kiota-authentication-spfx';
import {
ImageFit,
MessageBar, PersonaSize
} from '@fluentui/react';
import {
DocumentCard,
DocumentCardDetails,
DocumentCardPreview,
DocumentCardTitle,
IDocumentCardPreviewProps,
DocumentCardType,
} from '@fluentui/react/lib/DocumentCard';
import { Facepile, IFacepilePersona } from '@fluentui/react/lib/Facepile';
export default class TeamsList extends React.Component<ITeamsListProps, ITeamsListState> {
// #region ******************** UPDATE WITH YOUR TENANT DATA ********************
private readonly azureAdApplicationIdUri: string = "api://{AZURE_AD_CLIENT_ID}";
private readonly apiHost: string = "{YOUR_API}.azurewebsites.net";
// #endregion
constructor(props: ITeamsListProps) {
super(props);
this.state = {
teams: []
};
}
public componentDidMount(): void {
this.props.aadTokenProviderFactory.getTokenProvider()
.then((tokenProvider: AadTokenProvider): void => {
const authProvider =
new AzureAdSpfxAuthenticationProvider(
tokenProvider,
this.azureAdApplicationIdUri,
new Set<string>([
this.apiHost
]));
const adapter = new FetchRequestAdapter(authProvider);
adapter.baseUrl = `https://${this.apiHost}`;
const teamifiedClient = new TeamifiedApiClient(adapter);
teamifiedClient.teams.get().then(teams => {
console.log(teams);
this.setState({
teams: teams
});
})
.catch(e => {console.log(e)});
})
.catch(e => {console.log(e)});
}
public render(): React.ReactElement<ITeamsListProps> {
const {
isDarkTheme,
environmentMessage,
hasTeamsContext,
userDisplayName
} = this.props;
const teams = this.state.teams.length > 0 ?
<div className={styles.wrapper}>{this.state.teams.map((t, i) => {
const imageIndex = 100 + i;
const previewProps: IDocumentCardPreviewProps = {
previewImages: [
{
previewImageSrc: `https://picsum.photos/id/${imageIndex}/318/150`,
imageFit: ImageFit.cover,
width: 318,
height: 150,
},
],
};
const personas: IFacepilePersona[] = t.members.map(m => {
const nameSplit: string[] = m.displayName.split(' ');
const firstNameInitial: string = nameSplit[0].substring(0, 1).toUpperCase();
const lastNameInitial: string = nameSplit[1] ? nameSplit[1].substring(0, 1).toUpperCase() : '';
const persona: IFacepilePersona = {
personaName: m.displayName,
imageInitials: `${firstNameInitial} ${lastNameInitial}`
}
return persona;
});
return (
<DocumentCard key={t.id} type={DocumentCardType.normal}>
<DocumentCardDetails>
<DocumentCardPreview {...previewProps} />
<DocumentCardTitle title={t.displayName} />
<DocumentCardTitle title={t.description} showAsSecondaryTitle shouldTruncate />
<Facepile personas={personas} personaSize={PersonaSize.size24} className={styles.facepile} />
</DocumentCardDetails>
</DocumentCard>);
})}
</div> : <div>Loading data...</div>
return (
<section className={`${styles.teamsList} ${hasTeamsContext ? styles.teams : ''}`}>
<div className={styles.welcome}>
<img alt="" src={isDarkTheme ? require('../assets/welcome-dark.png') : require('../assets/welcome-light.png')} className={styles.welcomeImage} />
<MessageBar>Welcome, {escape(userDisplayName)}. {environmentMessage}</MessageBar>
</div>
<div>
{teams}
</div>
</section>
);
}
}

View File

@ -0,0 +1,11 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field",
"AppLocalEnvironmentSharePoint": "The app is running on your local environment as SharePoint web part",
"AppLocalEnvironmentTeams": "The app is running on your local environment as Microsoft Teams app",
"AppSharePointEnvironment": "The app is running on SharePoint page",
"AppTeamsTabEnvironment": "The app is running in Microsoft Teams"
}
});

View File

@ -0,0 +1,14 @@
declare interface ITeamsListWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
}
declare module 'TeamsListWebPartStrings' {
const strings: ITeamsListWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 B

View File

@ -0,0 +1,37 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.5/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"noImplicitAny": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}